Use KeyValueDiffers to detect changes in Angular objects

Use KeyValueDiffers to detect changes in Angular objects

ngDoCheck hook

ngDoCheckIt is one of the Angular life cycle hooks. It allows components to execute custom change detection logic when Angular detects changes.

ChangeDetectorRef.detectChanges()Angular calls the method when an input property of any component or directive changes, when a change detection cycle occurs within a component, or when a change detection strategy is actively triggered (such as via the method ) ngDoCheck.

Hooks can be used ngDoCheckto perform custom detection logic, but care needs to be taken not to abuse them. Since this hook will be triggered frequently, the complexity and resource consumption of its internal logic should be minimized.

Here's 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 (this.items && this.items.length !== this.itemCount) {
    
    
      this.itemCount = this.items.length;
    }
  }
}

In the above example, the interface CustomComponentis implemented DoCheckand the properties ngDoCheckare updated using methods itemCount. This component listens for itemschanges in the input attribute and updates the attribute if the length of the attribute changes itemCount. itemCountThis way, the component updates properties and re-renders the template in every change detection cycle .

KeyValueDiffersService

KeyValueDiffersIt is an injectable service in Angular that is used to detect changes in key-value pairs in objects.

When we need to monitor changes in one or some key-value pairs in an object, we can create an KeyValueDifferobject to listen for these changes. Inject the service in the component's constructor KeyValueDiffers, ngOnInit()use the service's find()method in the method to find the object to listen to, and use diff()the method to create an KeyValueDifferobject.

Here's a simple example:

import {
    
     Component, KeyValueDiffers, OnInit } from '@angular/core';

@Component({
    
    
  selector: 'app-custom-component',
  template: `
    <p *ngFor="let item of items">{
     
     { item.key }}: {
     
     { item.value }}</p>
  `
})
export class CustomComponent implements OnInit {
    
    
  items = [
    {
    
     key: 'name', value: 'John' },
    {
    
     key: 'age', value: 30 },
    {
    
     key: 'email', value: '[email protected]' }
  ];

  private differ: any;

  constructor(private differs: KeyValueDiffers) {
    
    }

  ngOnInit(): void {
    
    
    this.differ = this.differs.find(this.items).create();
  }

  ngDoCheck(): void {
    
    
    const changes = this.differ.diff(this.items);

    if (changes) {
    
    
      console.log('Changes detected!');
      // Handle changes here
    }
  }
}

In the above example, the service CustomComponentis injected in the component's constructor KeyValueDiffers. In ngOnInit()the lifecycle method, call differs.find()the method to find itemsthe array and use create()the method to create an KeyValueDifferobject.

Then, in the component's ngDoCheck()lifecycle method, diff()you check for changes to the key-value pairs in the object by calling the method and perform any necessary actions as needed. In actual projects, we can use this method to monitor some important states, such as changes in form controls, configuration items, etc.

Other uses of KeyValueDiffers

For KeyValueDiffersservices, here are some commonly used methods and properties:

  • find(): Find the corresponding one through the given object KeyValueDifferFactory. For example:this.differs.find(obj).create()
  • factories: Returns an array containing all registered ones KeyValueDifferFactory.
  • create(): Create an KeyValueDifferobject. For example:this.diff.create(obj)
  • differsKeyValueDiffers: Returns a service instance that can be injected .

KeyValueDifferContains the following methods:

  • diff(): Returns any updated key-value pairs, or null if there have been no changes.
  • onDestroy(): Clean up any resources. Like when Angular destroys this directive.

The main purpose of using KeyValueDiffersand KeyValueDifferis to perform some specific operations when certain key-value pairs in the object are detected to have changed. Similar to other change detection in Angular, KeyValueDiffersit can help us avoid unnecessary rendering problems caused by multiple modifications and improve application performance.

It should be noted that when using KeyValueDiffersand KeyValueDifferto monitor object changes, in order to improve performance, we should try to reduce the monitoring scope and only monitor the necessary parts to avoid unnecessary calculations and operations.

Guess you like

Origin blog.csdn.net/lin5165352/article/details/132567861