In this post, we will dive deep into the world of Signals in Angular 16, exploring their purpose, how they work within the framework, and providing step-by-step instructions on implementing them effectively in your projects.
What are Signals?
Signals were introduced in Angular 16 and enable developers to easily manage complex asynchronous operations and event-driven logic within their apps.
The primary purpose of Signals is to facilitate communication between different parts of an Angular application without relying on direct coupling between components or services. This promotes a more modular and maintainable codebase while also allowing for greater flexibility when it comes to handling complex scenarios.
Using Signals
Signals can be created in components, directives & services and you can read them directly from the template.
Creating a Signal
import { signal } from '@angular/core'
users = signal<{id: string, name: string}[]>([]);
The above syntax creates and initialises a signal using the signal constructor function.
Optionally, provide a generic type parameter to define the signal's data type. In many cases, the data type can be inferred and the generic type parameter is unnecessary.
Reading a Signal
users();
One way to read a signal is by using its name enclosed in parentheses, which invokes the getter function for that signal. In Angular, it is typical to retrieve signals in the template.
<p>{{ users().name; }}</p>
Changing the value of a Signal
To update the value of a signal, you can use the signal set method, which replaces the current value with a new one.
this.contacts.set(newContactArray);
Apart from the set() method, there are two other ways to modify a signal: update() and mutate().
When using the update() method, the signal is updated based on its current value. To do this, you can pass an arrow function to the update() method. This function takes the current signal value as its argument, allowing you to modify it as required. For instance, the code below doubles the value of the price signal:
price = signal<number>(10);
this.price.update(p => p * 2);
The mutate() method allows you to modify the content of a signal value rather than the signal value itself. This method is particularly useful for changing specific elements of an array or properties of an object.
To modify an array element or an object property, pass an arrow function to the mutate() method. The arrow function should modify the specific element or property as needed. For example, the code below adds a # symbol at the start of the users id:
this.users.mutate(c => c.id = `#${c.id}`);
Top comments (0)