This article mainly introduces to you the implementation method of using trackBy to improve performance in Angular. Friends who need it can refer to it. I hope it can help everyone.
When traversing a collection in an Angular template, you would write like this:
<ul> <li *ngFor="let item of collection">{{item.id}}</li> </ul>
Sometimes you will need to change the collection , such as returning new data from the backend interface. Then the problem comes, Angular doesn't know how to track the items in this collection, and doesn't know which ones should be added, which should be modified, and which ones should be deleted. As a result, Angular will remove all items from the collection and then add them again. Like this:
The disadvantage of this is that it will perform a large number of DOM operations, and DOM operations are very performance-consuming.
The solution is to add a trackBy function to *ngFor to tell Angular how to track the items of the collection. The trackBy function requires two parameters, the first is the index of the current item, the second is the current item, and returns a unique identifier, like this:
import{ Component } from '@angular/core'; @Component({ selector: 'trackBy-test', template: ` <ul><li *ngFor="let item of items; trackBy: trackByIndex">{{item.name}}</li></ul> <button (click)="getItems()">Get Items</button> ` }) export class TrackByCmp{ items: any[]=[]; constructor(){ this.items = [{name:'Tom'},{name:'Jerry'},{name:'Kitty'}]; } getItems(){ this.items = [{name:'Tom'},{name:'Jerry'},{name:'Mac'},{name:'John'}]; } trackByIndex(index, item){ return index; } }
After doing this, Angular knows which items have changed:
We can see that the DOM only redraws the modified and added items. Moreover, clicking the button again will not redraw it. But when the trackBy function is not added, repeated clicks on the button will still trigger redrawing (you can look back at the first GIF).
Related recommendations:
PHP improves performance through opcache
The above is the detailed content of Detailed explanation of how Angular uses trackBy to improve performance. For more information, please follow other related articles on the PHP Chinese website!