Writing Reactive Code with Signals in Angular.

Abhishek Khatri
2 min readMay 21, 2023

--

Angular Signals are a reactive primitive that can be used to improve the performance and readability of your Angular code. Signals are a way to notify interested consumers when a value changes. This can be useful for a variety of tasks, such as updating UI elements, running asynchronous code, or triggering events.

angular signals

To use Signals in Angular, you can use the signal() function. The signal() function takes a type parameter and returns a Signal instance. You can then use the Signal instance to get and set the value, and to subscribe to changes.

Here is an example of how to use Signals to update a UI element:

import { Component, OnInit } from '@angular/core';
import { signal } from '@angular/cdk/platform-browser';

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

// Create a signal to track the value of the counter
counterSignal = signal<number>(0);

constructor() {}

ngOnInit() {
// Subscribe to changes in the counter value
this.counterSignal.subscribe((value) => {
this.counter = value;
});
}

// Increase the counter value
increaseCounter() {
this.counterSignal.next(this.counter + 1);
}

}

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

<h1>Angular Signals Demo</h1>

<div>
The counter is {{ counter }}.
</div>

<button (click)="increaseCounter()">Increase Counter</button>

When you click the “Increase Counter” button, the counter value will be incremented. The counterSignal will then notify any subscribers of the change. In this case, the only subscriber is the AppComponent. The AppComponent will then update the value of the counter property, which will cause the counter element to be updated.

Signals can be used to improve the performance and readability of your Angular code. By using Signals, you can avoid the need to use change detection for small changes, and you can make your code more readable by using a reactive programming style.

--

--