Why Angular Signals? Write your first Angular Signal


Angular was the first JavaScript library to do change detection well.

🤓 🤓 🤓

That was back in the days of AngularJS, before React or Vue.js existed.

And since the first days the change detection and DOM manipulation methods have continuously improved.

That's why Angular recently got a new feature called Angular Signals.

Let's talk about it. 🤓

3d-fluency-gps-signal

What is a Signal?

The Angular signal is a new reactive primitive that allows you to build Angular apps in reactive style. It's basically a way to declare and use a dynamic value that evolves over time.

Let's use a simple example.

Imagine we have a simple increment Angular component.

Before Angular signals existed our code would look something like this.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [],
  template: `
    <button (click)="increment()">Increment</button>
    <p>{{ this.counter }}</p>
  `
})
export class AppComponent {
  counter = 0;
  increment() {
    this.counter++;
  }
}

When the increment button is clicked the Angular change detection mechanism automatically updates the HTML to match the new value of counter.

But with the Angular signal that all changes.

Our component would now look like this.

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

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [],
  template: `
    <button (click)="increment()">Increment</button>
    <p>{{ this.counter() }}</p>
  `
})
export class AppComponent {
  counter = signal(0);

  increment() {
    this.counter.set(this.counter() + 1);
  }
}

What we've taken is turned the counter variable into the signal type.

Why use Signals in the first place?

So why use Angular signals?

The benefit of Angular signals are simple: improve the performance of your Angular application.

With Angular signals it gives Angular a way of knowing when the data in an exact component is changed.

This allows Angular to "smartly" track the changes between data and the DOM in the applications.

When the signal changes Angular will know what components in the component tree should be marked as dirty and be updated. This allows for quicker change detection in Angular.

This is an improvement over the use of the zone.js library to manage change detection in Angular.

Zone.js doesn't have the ability to "smartly" detect what to change or update like the new signals feature in Angular.

So that is a quick introduction to Angular signals and why you should start using them.

Till later,

signature

Daniel Kreider - Angular Developer

Credits

Illustration by Icons 8 from Ouch!