ngDoCheck Example | Angular

Last modified: April 22, 2019

ngOnChanges Example

ngOnInit Example

ngDoCheck Example

ngAfterContentInit Example

ngAfterContentChecked Example

ngAfterViewInit Example

ngAfterViewChecked Example

ngOnDestroy Example

parent.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-parent',
  template: `<a (click)="updateUser()">Update</a><br/>
              <app-child [user]="user"></app-child>`
})
export class ParentComponent implements OnInit {
  user = {
    name:"Alex"
  }
  constructor() { }
  ngOnInit() {
  }
  updateUser(){
    this.user.name = "ted"
  }
}

child.component.ts

import { Component, OnInit, Input, ChangeDetectionStrategy, DoCheck, OnChanges } from '@angular/core';
@Component({
  selector: 'app-child',
  template: `Here is the user name: {{ user.name }}`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnInit {
  @Input() user;
  constructor() { }
  ngOnInit() {
  }
  ngOnChanges(){
    console.log("CHANGES")
  }
  ngDoCheck(){
    console.log("DO CHECK")
  }
}

ngDoCheck() is called whenever change detection is run.

ngDoCheck() is called immediately after ngOnChanges() and ngOnInit()

Notice how our ChildComponent implements an OnPush change detection strategy. This means {{ user.name }} won't update unless the reference to @Input() user changes.

Setting this.user.name = "ted" doesn't change the reference to user. This means ngOnChanges() won't fire from the child component but ngDoCheck() will.

When should you use ngDoCheck?

Use ngDoCheck when you want to capture changes that Angular otherwise doesn't.

For example, if a binding references remains unchanged after a click event, ngOnChanges won't run but ngDoCheck will.

You might also like: