Skip to content Skip to sidebar Skip to footer

Angular Components: Using and understanding Signals in Angular 17+

Angular Signals is a system that granularly tracks how and where your data or state is used throughout an application, allowing the framework to optimize rendering updates.

Angular continues to evolve with Signal-based APIs, introducing a cleaner, more declarative, and reactive approach to building components. In this blog post we will try to understand these feature with practical examples.

Before introducing signal, developers were using RxJs Subject and BehaviorSubject to work with reactive data handling and data sharing between multiple components.

Code example:

Before signal we were using RxJs Observables:

import { BehaviorSubject } from ‘rxjs’;export class MyService {

private myStateSubject = new BehaviorSubject(‘initial state’);

myState$ = this.myStateSubject.asObservable();

updateState(newState: string) {

this.myStateSubject.next(newState);

}
}

With Signals:

import { signal } from ‘@angular/core;export class MyService {    private myState = signal(‘initial state’);get state() {

return this.myState.get();

}

updateState(newState: string) {

this.myState.set(newState);

}
}

Understanding how Signals Work?

  • Angular.com describes Signals as wrappers. It is explained that signals wrap around a value. To simply put, it is like an eggshell that holds the egg yolk wrapped in it.
  • Angular signals wrap around a value (holds a value) and then notifies the user of any changes. Then to read the value from a signal you need a special function called a getter.
  • There are two types of signals: Writable Signals and Computed Signals (read-only):

Writable signals:

public count = signal(0);console.log(‘The count is: ‘ + this.count());// OUTPUT : The count is: 0

1. To change the value of a writable signal, either use .set() method directly like

this.count.set(3);console.log(‘The count is: ‘ + this.count());// OUTPUT : The count is: 3or use the .update() operation to compute a new value from the previous one:

// Increment the count by 1.

this.count.update(value => value + 1);console.log(‘The count is: ‘ + this.count());// OUTPUT: The count is: 4

Computed signals:

Computed signal are read-only signals that derive their value from other signals. You define computed signals using the computed function and specifying a derivation:

import { Component, computed, signal, WritableSignal } from ‘@angular/core’;@Component({selector: ‘app-root’,

standalone: true,

templateUrl: ‘./app.component.html’,

styleUrl: ‘./app.component.scss’

})

export class AppComponent {

public count: WritableSignal = signal(10);

public doubleCount = computed(() => this.count() * 2);

constructor() {

console.log(“Double Count value is: “, this.doubleCount());

}

}

// OUTPUT:

// Double Count value is:  20

Leave a comment