Thi Notes
AboutNotesBlogTopicsToolsReading
About|Sketches |Cooking |Cafe icon Support Thi

Understand changeDetection in Angular

Understand changeDetection in Angular

Anh-Thi Dinh
draft
Angular
⚠️
This is a quick & dirty draft, for me only!
This note is for understanding changeDetection strategy in Angular with examples.
πŸ‘‰Β Angular - ChangeDetectionStrategy
πŸ‘‰ Angular - ChangeDetectorRef
  • How to use?
    • 1@Component({
      2  // ... others
      3  changeDetection: ChangeDetectionStrategy.OnPush 
      4  // default to .Default (CheckAlways)
      5  // .OnPush (CheckOnce)
      6})
      7export class NameOfComponent implements OnInit {}
  • Good to read: angular - What's the difference between markForCheck() and detectChanges() - Stack Overflow
  • .Default ensures the accuracy (view updated when having changes), it can lead to performance β†’ use .OnPush to optimize!
  • When the view is detached from the change-detection tree, we use detach() in combination with detectChanges().
  • When for some reason, the view isn’t reflected with the changes, use detectChanges()!
  • Use markForCheck() whenever use ChangeDetectionStrategy.OnPush!
  • If you want to detach change detector to limit how often check occurs (and reattach later), read the official guide.