💻 Tech
Angular uses zonejs to manage state changes that are bound to the UI. It uses the concept of “zones” where Angular checks all the places and update them whenever data bound to the UI are updated. Starting with Angular 16, Signals are now available for use as an alternative to the Angular’s default state detection with zonejs.
Signals are more efficient than the default state management as Angular will only need to check the places where signals are used.
In the example below, signal
is imported and used to declare the variable user
. Use set
method to update the value of user
. With every change, the UI is automatically updated. To get the value of the signal as demonstrated by the HTML code, get the signal via user()
and access the property name
from the user
object returned by the signal.
<div>
<button (click)="onButtonClick()">
<span>{{user().name}}</span>
</button>
</div>
import { Component, signal } from '@angular/core';
import { generateUser } from '../user_generator';
@Component({
selector: 'app-user',
standalone: true,
imports: [],
templateUrl: './user.component.html',
styleUrl: './user.component.css'
})
export class UserComponent {
user = signal(generateUser())
onButtonClick(){
user = user.set(generateUser());
}
}