Angular Signals: A New Way to Manage State in Angular Applications

Introduction

Angular v16 introduces a new way to manage state in Angular applications called Signals. Signals are a more lightweight and flexible alternative to Angular's built-in Change Detection mechanism. Signals can be used to track changes to data in your application and trigger the re-rendering of components only when necessary. This can lead to significant performance improvements in large applications.

How to Use Angular Signals?

To use Signals, you first need to import the Signal class from the @angular/core library. Once you have imported the Signal class, you can create a new signal by calling the new Signal() constructor. The new Signal() constructor takes one argument, which is the initial value of the signal.

Once you have created a new signal, you can subscribe to it by calling the subscribe() method. The subscribe() the method takes a callback function as its argument. The callback function will be called whenever the value of the signal changes.

You can also use signals to create computed values. Computed values are derived values that are updated whenever the values of their dependencies change. To create a computed value that depends on a signal, you use the | async pipe.

Example

The following example shows how to use Signals to track changes to a user's name and age.

import { Component, OnInit } from '@angular/core';
import { Signal } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  name = new Signal('');
  age = new Signal(0);

  constructor() {}

  ngOnInit() {
    this.name.subscribe(() => {
      console.log('Name changed to', this.name.value);
    });

    this.age.subscribe(() => {
      console.log('Age changed to', this.age.value);
    });
  }

}

The app.component.html file contains the following code.

<h1>Angular Signals Demo</h1>

<input [(ngModel)]="name" placeholder="Enter your name">

<h2>Age</h2>

<input [(ngModel)]="age" placeholder="Enter your age">

When the user changes the value of the name or age input, the corresponding signal will be updated. The callback function that is subscribed to the signal will then be called. In this case, the callback function will log the new value of the signal to the console.

Conclusion

Angular Signals is a powerful new tool for managing state in Angular applications. Signals can be used to track changes to data in your application and trigger the re-rendering of components only when necessary. This can lead to significant performance improvements in large applications.


Similar Articles