The number of methods called in a sequence to execute a component at specific moments is known as lifecycle hook.
constructor
ngOnChanges( )
ngOnInit( )
ngDoCheck( )
ngAfterContentInit( )
ngAfterContentChecked( )
ngAfterViewInit( )
ngAfterViewChecked( )
ngOnDestroy( )
Two-way data-binding
Unidirectional data flow
Angular separates updating the application model and reflecting the state of the model in the view into two distinct phases. The developer is responsible for updating the application model. Angular, by means of change detection, is responsible for reflecting the state of the model in the view.
under the hood angular uses a low-level abstraction called view.
export class AppComponent {
constructor(cd: ChangeDetectorRef) { ... }
export declare abstract class ChangeDetectorRef {
abstract checkNoChanges(): void;
abstract detach(): void;
abstract detectChanges(): void;
abstract markForCheck(): void;
abstract reattach(): void;
}
export abstract class ViewRef extends ChangeDetectorRef {
...
}
So in short :
Use detectChanges() when you've updated the model after angular has run it's change detection, or if the update hasn't been in angular world at all.
Use markForCheck() if you're using OnPush and you're bypassing the ChangeDetectionStrategy by mutating some data or you've updated the model inside a setTimeout;
NgZone.runOutsideAngular
@Component({
selector: 'r-comp',
template: `{{addRender()}}`
})
export class RComponent {
ngDoCheck() {
// holds all calls in order and is logged to console
calls.ngDoCheck.push('R');
}
@Component({
selector: 'r-comp',
template: `{{addRender()}}`
})
export class RComponent {
addRender() {
calls.render.push('R');
}
}
When Angular checks the current component it calls lifecycle hooks on child components, but renders DOM for the current component.