Angular’s Signal Revolution: Effortless Change Detection Explained — Unveiling the Inner Workings
<p>Angular’s signals bring a host of benefits to the table, one of which is their ability to seamlessly integrate with templates and “automate” change detection. This automation means that a component configured with the <code>OnPush</code> change detection strategy will be rechecked during the next change detection cycle, sparing developers from manually injecting <code>ChangeDetectorRef</code> and invoking <code>markForCheck</code>. To illustrate this advantage, consider the following example:</p>
<pre>
@Component({
selector: 'app-foo',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `{{ num }}`,
})
export class FooComponent {
num = 1;
private cdr = inject(ChangeDetectorRef);
ngOnInit() {
setTimeout(() => {
this.num = 2;
this.cdr.markForCheck();
}, 3000);
}
}</pre>
<p>Here, we explicitly inject <code>ChangeDetectorRef</code> and invoke <code>markForCheck</code> after updating the component's state. The new way with signals:</p>
<pre>
@Component({
selector: 'app-foo',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `{{ num() }}`,
})
export class FooComponent {
num = signal(0)
ngOnInit() {
setTimeout(() => this.num.set(1), 3000);
}
}</pre>
<p>In this improved version, we use a <code>signal</code>, and remarkably, the view still updates without needing to manually call <code>markForCheck</code>. In this article, we will delve into the inner workings of this feature, shedding light on how signals streamline change detection in Angular applications.</p>
<p>At a higher level of abstraction, you can conceptualize the current template as the <code>consumer</code> and every signal as the <code>producer</code>. When a signal undergoes a value change, it promptly notifies the template, which subsequently triggers a call to <code>markForCheck</code>.</p>
<p><a href="https://netbasal.com/angulars-signal-revolution-effortless-change-detection-explained-unveiling-the-inner-workings-8a5e44c95b65">Click Here</a></p>