angular tutorials

Why do we need ngDoCheck lifecycle hook – Angular ?

This tutorial guides you on what is ngDoCheck and why do we need ngDoCheck lifecycle hook in Angular. 

What is ngDoCheck ?

It is a callback method which will get called by Angular after every default change detection runs and it can be used to perform change-detection. The default change detection algorithm checks for bound-property changes.

When the default change detector runs, it calls ngOnChanges() lifecycle hook i.e., ngOnChanges() will get called after a bound-property changes.

And ngDoCheck lifecycle hook will get called after the following lifecycle hooks get invoked; ngOnChanges() and ngOnInit().

  • ngOnChanges() – Invoked after a bound input property changes.
  • ngOnInit – Invoked once the component is initialized.
  • ngDoCheck – Invoked after every change detection run
ngDoCheck(): void

Parameters
There are no parameters.

Returns
void

Why do we need ngDoCheck lifecycle hook ?

DoCheck is a lifecycle hook used to invoke a custom change-detection function for a directive. This can be used in addition to the default change-detection run performed by the Angular’s default change-detector.

And when the default change detector detects the bound-property changes, it invokes ngOnChanges() as mentioned above whether you perform any additional change detection or not. Also, note you should not use both DoCheck and OnChanges in order to check changes on the same input.

The following sneppet shows how to use ngDoCheck in your component to call or invoke it’s own change-detection cycle or custom change-detection function.

@Component({selector: 'my-component', template: `...`})
class MyComponent implements DoCheck {
  ngDoCheck() {
    // ...
  }
}

For example, to check changes that happens where ngOnChanges() can’t catch them, you can implement your own custom change-detection check as shown below.

ngDoCheck() {

  if (this.title.name !== this.oldTitleName) {
    this.changeDetected = true;
    this.changeLog.push(`DoCheck: Title name changed to "${this.title.name}" from "${this.oldTitleName}"`);
    this.oldTitleName= this.title.name;
  }
  ----
  ----
  this.changeDetected = false;
}

That’s it. You have learnt what is ngDoCheck and why do we need ngDoCheck lifecycle hook in Angular.

Hope it helped 🙂

Also See:

References:

Leave a Reply

avatar
  Subscribe  
Notify of