This note is for understanding
changeDetection
strategy in Angular with examples.- 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 withdetectChanges()
.
- When for some reason, the view isn’t reflected with the changes, use
detectChanges()
!
- Use
markForCheck()
whenever useChangeDetectionStrategy.OnPush
!
- If you want to detach change detector to limit how often check occurs (and reattach later), read the official guide.