Developers can harness reactivity through signals.
Signals play a crucial role in reducing dependency on zone.js
for change detection, making Angular lighter as the team moves towards "Zoneless Angular."
Efficiently updating data and reacting to changes on the source signal is best achieved with signals.
When a signal value changes, it triggers linked properties/actions to execute.
To fully utilize the power of signals, integrating with ChangeDetectionStrategy.OnPush
is recommended for improved performance due to caching of computed
.
While the normal way of doing Angular works, exploring the benefits of signals presents a superior alternative.
Consider the example of utilizing computed
. Computed signals allow for deriving a state variable based on other state variables.
@Component({
template: `
<app-child [(ngModel)]="beep" />
`,
})
export class Parent {
protected beep = signal("signals");
protected computedSignal = computed(() => {
const beepVal = this.beep();
return beepVal * 2;
});
}
If the computation within the top function is resource-intensive, using computed signals optimizes resource usage as they are both lazily evaluated and memoized (source).
Even with multiple change detections firing, the computation occurs only once until watched signals alter, prompting a fresh evaluation.
Another important example is the use of effect
, ideal for responding to signal changes and executing side effects.
Although setting a signal inside an effect isn't possible, leveraging observables recalculates when the signal changes.
@Component({
template: `
<app-child [(ngModel)]="beep" />
`,
})
export class Parent {
protected beep = signal("signals");
protected beepDetails$ = of([]);
constructor() {
effect(() => {
if(this.beep() > 100) {
this.popupService.show('beep value cannot be greater than 100);
}
});
}
}
In the presented scenario, any change in the beep signal triggers validation ensuring the value doesn't exceed 100, accompanied by a popup notification.
This overview merely scratches the surface; for a comprehensive guide, visit angular.dev