Angular???s Signal Revolution: Effortless Change Detection Explained?????????Unveiling the Inner Workings

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 OnPush change detection strategy will be rechecked during the next change detection cycle, sparing developers from manually injecting ChangeDetectorRef and invoking markForCheck. To illustrate this advantage, consider the following example:

@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);
  }
}

Here, we explicitly inject ChangeDetectorRef and invoke markForCheck after updating the component's state. The new way with signals:

@Component({
  selector: 'app-foo',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `{{ num() }}`,
})
export class FooComponent {
  num = signal(0)

  ngOnInit() {
    setTimeout(() => this.num.set(1), 3000);
  }
}

In this improved version, we use a signal, and remarkably, the view still updates without needing to manually call markForCheck. In this article, we will delve into the inner workings of this feature, shedding light on how signals streamline change detection in Angular applications.

At a higher level of abstraction, you can conceptualize the current template as the consumer and every signal as the producer. When a signal undergoes a value change, it promptly notifies the template, which subsequently triggers a call to markForCheck.

Click Here