SoFunction
Updated on 2025-04-08

Detailed explanation of using KeyValueDiffers to detect changes in Angular objects

ngDoCheck hook

ngDoCheckis one of the Angular life cycle hooks. It allows components to perform custom change detection logic when Angular detects changes.

When the input properties of any component or instruction change, a change detection cycle occurs within the component, or when the change detection strategy is actively triggered (e.g. through()Angular will callngDoCheckmethod.

Can be usedngDoCheckHooks to perform custom detection logic, but be careful not to abuse it. Since the hook is triggered frequently, the complexity of its internal logic and resource consumption should be minimized.

Here is a simple example:

import { Component, Input, DoCheck } from '@angular/core';
@Component({
  selector: 'app-custom-component',
  template: `
    <p>{{ name }} has {{ itemCount }} items.</p>
  `
})
export class CustomComponent implements DoCheck {
  @Input() name: string;
  @Input() items: any[];
  itemCount: number;
  ngDoCheck(): void {
    if ( &&  !== ) {
       = ;
    }
  }
}

In the example above,CustomComponentImplementedDoCheckinterface and usengDoCheckMethod updateitemCountproperty. This component listens for input propertiesitemsChanges, if the length of the property changes, updatesitemCountproperty. This way, the component will be updated in each change detection cycleitemCountProperties and re-render the template.

KeyValueDiffers Service

KeyValueDiffersIs an injectable service in Angular that detects changes in key-value pairs in an object.

When we need to monitor changes in a certain key-value pair in an object, we can create aKeyValueDifferObjects to listen for these changes. Inject in component constructorKeyValueDiffersService, inngOnInit()The method uses the servicefind()Method to find the object to be listened to and usediff()Method to create aKeyValueDifferObject.

Here is a simple example:

import { Component, KeyValueDiffers, OnInit } from '@angular/core';
@Component({
  selector: 'app-custom-component',
  template: `
    <p *ngFor="let item of items">{{  }}: {{  }}</p>
  `
})
export class CustomComponent implements OnInit {
  items = [
    { key: 'name', value: 'John' },
    { key: 'age', value: 30 },
    { key: 'email', value: 'john@' }
  ];
  private differ: any;
  constructor(private differs: KeyValueDiffers) {}
  ngOnInit(): void {
     = ().create();
  }
  ngDoCheck(): void {
    const changes = ();
    if (changes) {
      ('Changes detected!');
      // Handle changes here
    }
  }
}

In the example above,CustomComponentInjected into the component's constructorKeyValueDiffersServe. existngOnInit()In the life cycle method, call()Methods founditemsArray and usecreate()Method to create aKeyValueDifferObject.

Then, in the componentngDoCheck()In the life cycle method, by callingdiff()Methods check the changes in key-value pairs in the object and perform any necessary operations as needed. In actual projects, we can use this method to listen for some important states, such as changes in form controls, configuration items, etc.

Other usages of KeyValueDiffers

forKeyValueDiffersServices, the following are some commonly used methods and properties:

  • find(): Find the corresponding object through the given objectKeyValueDifferFactory. For example:(obj).create()
  • factories: Returns an array containing all registeredKeyValueDifferFactory
  • create(): Create aKeyValueDifferObject. For example:(obj)
  • differs: Returns an injectableKeyValueDiffersService instance.

KeyValueDifferIncludes the following methods:

  • diff(): Returns any updated key-value pairs, or null if no changes are made.
  • onDestroy(): Clean up any resources. Just like when Angular destroys this instruction.

useKeyValueDiffersandKeyValueDifferThe main purpose is to perform some specific operations when certain key-value pairs in the object are detected to change. Similar to other change detections in Angular,KeyValueDiffersIt can help us avoid unnecessary rendering problems caused by multiple modifications and improve application performance.

It should be noted that when usingKeyValueDiffersandKeyValueDifferWhen listening for changes in objects, in order to improve performance, we should try to minimize the listening range and only listen to necessary parts to avoid unnecessary calculations and operations.

The above is a detailed explanation of the use of KeyValueDiffers to detect changes in Angular objects. For more information about KeyValueDiffers to detect Angular, please follow my other related articles!