I still do not understand what is the difference between cdr.detectChanges()
and cdr.markForCheck()
for OnPush
change detection strategy from the usage view.
Eventhough I have read this SO question and InDepth explanation.
Why can't I just call cdr.detectChanges()
?
Why do I need to mark the tree from current component to the root (Or is it due to postpone to the next detection cycle)?
Or is it somehow required to update parent components too?
In the following example, both ways works:
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
template: `{{ i }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestComponent implements OnInit {
private i = 0;
constructor(private cdr: ChangeDetectorRef) { }
ngOnInit() {
setInterval(() => {
this.i++;
// this.cdr.detectChanges(); // this works too and updates view
this.cdr.markForCheck(); // but this is for some reason recommended
}, 1000);
}
}