Signals are a reactive data model that provides a simple way to manage and track changes in state within an application. A Signal in Angular is a variable whose value can change over time and any change to this value will automatically propagate to the parts of the application that depend on it.
Key Concepts
- Signals: A reactive primitive that holds a value and notifies subscribers when the value changes.
- Effects: Functions that automatically re-run when the signals they depend on change effects can be used to trigger side effects based on signal changes.
- Signal Equality Functions: These are functions that compare the new values of a signal to its previous value to determine whether an update should trigger a re-run or effects or re-rendering.
- Effect Cleanup Functions: Functions that are called to clean up any side effects or resources when an effect re-runs or when the component is destroyed.
Prerequisites
To understand this article you have basic knowledge in the below listed topics.
Here we provide a list possible Approaches for creating Signals in Angular framework.
Creating Signals using the signal function
The signal function is used to create a reactive data source. This data source can be used in templates or component logic and It automatically updates whenever the signals value changes.
Syntax
const mySignal = signal(initialValue);
Example
import { signal } from '@angular/core';
const counterSignal = signal(0);
// Increment the counter
counterSignal.update(count => count + 1);
// Get the current value
console.log(counterSignal()); // Outputs: 1
- signal (initialValue): Creates a new signal with an initial value.
- counterSignal.update (fn): Updates the signal using the provided function.
- counterSignal(): Retrieves the current value of the signal.
Creating Computed Signals using the computed function
The computed function is used to create a signal that delivers its value other signals and It automatically recalculates whenever any of the dependent signals change.
Syntax
const myComputedSignal = computed(() => /* expression based on other signals */);
Example
import { signal, computed } from '@angular/core';
const x = signal(2);
const y = signal(3);
const sum = computed(() => x() + y());
console.log(sum()); // Outputs: 5
// Update one of the signals
x.set(5);
console.log(sum()); // Outputs: 8 (since x is now 5 and y is 3)
- computed(() => /* expression */): Creates a computed signal based on other signals.
- sum(): Retrieves the current computed value, which is automatically updated when x or y changes.
Using Effects
Effect functions are a way to watch for changes in signals and trigger specific code when those changes occur. An effect is automatically re run whenever any signal it depends on changes.
Example
import { effect, signal } from '@angular/core';
const count = signal(0);
// Define an effect that logs the count whenever it changes
effect(() => {
console.log(`Count changed to: ${count()}`);
});
// Update the signal value
count.set(1); // Logs: "Count changed to: 1"
Signal Equality Functions
These functions are used to optimize reactivity by determining if the value of a signal has actually changed. If the equality function returns false angular can avoid unnecessary updates.
Example
import { signal, signalEquality } from '@angular/core';
const mySignal = signal({ x: 10, y: 20 }, { equals: (a, b) => a.x === b.x && a.y === b.y });
mySignal.set({ x: 10, y: 20 }); // No effect triggered, as the values are considered equal
mySignal.set({ x: 15, y: 20 }); // Effect triggered, as the x value has changed
Effect Cleanup Functions
When an effect function is re run due to a change in one of its signals a cleanup function can be used to clean up resources or side effects from the previous run before the new effect is executed.
Example:
import { effect, signal } from '@angular/core';
const count = signal(0);
effect((onCleanup) => {
const interval = setInterval(() => {
console.log(`Interval count: ${count()}`);
}, 1000);
// Define the cleanup function to clear the interval
onCleanup(() => clearInterval(interval));
});
count.set(1); // Triggers re-run, and the old interval is cleared
Steps to Create Angular Application
Here we first created a new angular application once project is created successfully then we develop logic for signals. For achieving Signals in Angular follow below step by step process.
Step 1 : Create a New Angular Application
First create a new Angular Application by using below command. Once project is created navigate to project folder.
ng new angular-signals-demo
cd angular-signals-demo
Folder StructureStep 2 : Update the Application to Use Signals
Signals are part of the Angular core, so no additional modules need to be installed. You can directly use the signal and computed functions.
Step 3: Implement Signals in Application
To implement signals in our application we need to change below listed files in the project folder.
HTML
<!-- src/app/app.component.html -->
<h1>Angular Signals Example</h1>
<p>Counter: {{ counter() }}</p>
<button (click)="increment()">Increment</button>
<p>Double: {{ doubleCounter() }}</p>
CSS
/* src/app/app.component.css */
h1 {
color: #333;
}
button {
margin-top: 10px;
}
JavaScript
// src/app/app.component.ts
import { Component } from '@angular/core';
import { signal, computed } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true, // This ensures the component is standalone
templateUrl: './app.component.html', // External template file
styleUrls: ['./app.component.css'] // External stylesheet file
})
export class AppComponent {
// Define signals
counter = signal(0);
doubleCounter = computed(() => this.counter() * 2);
// Method to increment the counter
increment() {
this.counter.update(count => count + 1);
}
}
Step 4: Run the Application
Once development is completed now run the angular application by using below command.
ng serve
Output
Once project is successfully running now test the application. When you run this application. The UI will display the initial counter value which is 0 when you click on the increment button the counter will increate by 1 and the double counter value updated automatically to reflect twice the value of the counter.
Similar Reads
Pipes in Angular
Pipes are often used for formatting dates, numbers, and Strings and they can be customized to suit various needs. In this article, we explain about how to use pipes in Angular with examples and related outputs for your reference.Prerequisites:To understand this article you should have knowledge of t
8 min read
Angular Versions
Angular has been an essential framework in web development, enabling developers to build dynamic and responsive web applications. Since its launch, Angular has evolved, introducing new features, performance improvements, and enhanced capabilities. Understanding the different versions of Angular and
3 min read
Angular Material Icons
Angular Material is a UI component library that is developed by Google so that Angular developers can develop modern applications in a structured and responsive way. By using this library, we can significantly increase an end-users user experience, thereby gaining popularity for our application. Thi
5 min read
Angular Signals - debounce in effect()
In Angular, the effect() function creates side effects based on reactive signal values. The debounce operator is a powerful tool that can be used with effect() to control the rate at which the side effect is triggered. Debouncing is a technique that delays the execution of a function until a certain
3 min read
What is Angular ?
Angular is an open-source web application framework maintained by Google and a community of developers. It is designed to build dynamic and interactive single-page applications (SPAs) efficiently. With Angular, developers can create robust, scalable, and maintainable web applications. Table of Conte
5 min read
Updates in Angular 12
Angular 12 is the latest version of the popular front-end web development framework. Angular released in May 2021 comes with several new features and improvements that enhance the performance, productivity, and stability of the framework. In this article, we will see different key features and impro
5 min read
Angular Tutorial
Angular is a powerful, open-source web application framework for building dynamic and scalable single-page applications (SPAs). Developed by Google, Angular provides a comprehensive solution for front-end development with tools for routing, form handling, HTTP services, and more.Designed for buildin
4 min read
News App Using Angular
We will be developing a News Application using the Angular framework. This interactive app will allow users to search for news articles and filter them by category. With a clean and responsive design, it will dynamically display articles, providing an engaging and user-friendly experience. The app w
9 min read
AngularJS Data Binding
In this article, we will see the Data Binding in AngularJS, along with understanding the various types of Data Binding available with their implementations. Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a
4 min read
What is View in AngularJS ?
In AngularJS, the View is what the user can see on the webpage. In an application (as per the userâs choice), the chosen view is displayed. For this purpose, the ng-view directive is used, which allows the application to render the view. Any changes made in the view section of the application are re
7 min read