0
0
Angularframework~5 mins

ngDoCheck for custom change detection in Angular

Choose your learning style9 modes available
Introduction

Sometimes Angular's automatic change detection does not catch all changes. ngDoCheck lets you check for changes yourself and react to them.

You want to detect changes in objects or arrays that Angular does not track by default.
You need to run custom logic when some data changes, but Angular's default checks miss it.
You want to optimize performance by controlling when and how change detection runs.
You have complex data structures and want to detect deep changes manually.
Syntax
Angular
ngDoCheck(): void {
  // Your custom change detection logic here
}

This method is part of Angular's DoCheck lifecycle interface.

Angular calls ngDoCheck frequently, so keep logic efficient.

Examples
Check if a simple value changed and react to it.
Angular
ngDoCheck(): void {
  if (this.oldValue !== this.newValue) {
    console.log('Value changed!');
    this.oldValue = this.newValue;
  }
}
Detect changes in an array's length manually.
Angular
ngDoCheck(): void {
  const currentLength = this.items.length;
  if (this.oldLength !== currentLength) {
    console.log('Array length changed!');
    this.oldLength = currentLength;
  }
}
Sample Program

This component uses ngDoCheck to detect when the items array changes length. When you click the button, a new item is added, and the console logs the change.

Angular
import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-custom-check',
  template: `
    <h2>Custom Change Detection Example</h2>
    <button (click)="addItem()">Add Item</button>
    <ul>
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>
  `
})
export class CustomCheckComponent implements DoCheck {
  items: string[] = ['Apple', 'Banana'];
  oldLength = this.items.length;

  ngDoCheck(): void {
    if (this.oldLength !== this.items.length) {
      console.log('Items array changed!');
      this.oldLength = this.items.length;
    }
  }

  addItem() {
    this.items.push('Orange');
  }
}
OutputSuccess
Important Notes

Do not put heavy or slow code inside ngDoCheck because it runs often.

Use ngDoCheck only when Angular's default change detection is not enough.

Summary

ngDoCheck lets you run your own checks for changes.

It is useful for detecting changes Angular misses, like in arrays or objects.

Keep the code inside ngDoCheck fast and simple.