Use KeyValueDiffers to detect changes in Angular objects
ngDoCheck hook
ngDoCheck
It 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 ngDoCheck
to 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 CustomComponent
is implemented DoCheck
and the properties ngDoCheck
are updated using methods itemCount
. This component listens for items
changes in the input attribute and updates the attribute if the length of the attribute changes itemCount
. itemCount
This way, the component updates properties and re-renders the template in every change detection cycle .
KeyValueDiffersService
KeyValueDiffers
It 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 KeyValueDiffer
object 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 KeyValueDiffer
object.
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 CustomComponent
is injected in the component's constructor KeyValueDiffers
. In ngOnInit()
the lifecycle method, call differs.find()
the method to find items
the array and use create()
the method to create an KeyValueDiffer
object.
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 KeyValueDiffers
services, here are some commonly used methods and properties:
find()
: Find the corresponding one through the given objectKeyValueDifferFactory
. For example:this.differs.find(obj).create()
factories
: Returns an array containing all registered onesKeyValueDifferFactory
.create()
: Create anKeyValueDiffer
object. For example:this.diff.create(obj)
differs
KeyValueDiffers
: Returns a service instance that can be injected .
KeyValueDiffer
Contains 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 KeyValueDiffers
and KeyValueDiffer
is 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, KeyValueDiffers
it can help us avoid unnecessary rendering problems caused by multiple modifications and improve application performance.
It should be noted that when using KeyValueDiffers
and KeyValueDiffer
to 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.