Home > Article > Web Front-end > How to improve performance using trackBy in Angular
This article mainly introduces the implementation method of using trackBy to improve performance in Angular. Friends who need it can refer to it
When traversing a collection (collection) in Angular template, you would write like this :
<ul> <li *ngFor="let item of collection">{{item.id}}</li> </ul>
Sometimes you will need to change this 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 each item of the collection. The trackBy function takes 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 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).
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Use native JavaScript to achieve the magnifying glass effect
Encapsulated cache class implemented through redis as a cache in nodejs
Use bcryptjs password encryption in Express
Use icon icon through Element in Vue
Use How does Vue.set() implement dynamic response to data
How to implement dynamic binding of images and data return image paths in vue
The above is the detailed content of How to improve performance using trackBy in Angular. For more information, please follow other related articles on the PHP Chinese website!