Blog

ngDoCheck Example | Angular

Key Takeaways

  • ngDoCheck() allows you to manually implement change detection if Angular's default detection would overlook it.
  • It's especially useful with the OnPush change detection strategy as it skips change detection when object references haven't changed.
  • Use ngDoCheck() for deep checking or complex detections that Angular doesn't handle automatically.

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

ngDoCheck() is invoked during every change detection cycle.

ngDoCheck() runs immediately after Angular checks its components for changes.

Our ChildComponent uses an OnPush change detection strategy. With this setting, Angular's change detection doesn't re-run unless input references change, so simply modifying a property like this.user.name = "ted" won't trigger ngOnChanges(), but it will trigger ngDoCheck().

When should you use ngDoCheck?

Use ngDoCheck() to handle changes Angular wouldn't detect on its own. This might be necessary if you're working with complex objects or nested structures where simply swapping references doesn't occur.

FAQ

Why doesn't ngOnChanges fire when I update a property?

ngOnChanges depends on Angular detecting changes at the reference level. If you're changing properties within an object but not the object itself, ngOnChanges won't detect this as a change.

Is ngDoCheck inefficient?

ngDoCheck can be resource-intensive because it runs with every change detection cycle. It's essential to use it judiciously and optimize any logic within this lifecycle hook to avoid performance hits.

How does change detection strategy OnPush affect ngDoCheck?

With OnPush, change detection only occurs when inputs change at the reference level, making ngDoCheck crucial when properties of these inputs need monitoring that OnPush wouldn't handle by default.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews