简体   繁体   中英

Angular: *ngFor trackby Date

my problem is, that I am Iterating over an Array of Dates in an Angular template. The reference of the Dates changes every time, so the view is redrawing what slows down the application. My idea was, to do a "trackby" with Date.getTime() but that doesn't work correctly. The DOM-Elements are recreated yet. That makes the site very slow.

Here's the code example:

<div *ngFor ="let month of (months$ | async); trackBy: trackByMonth">
... 
</div>

trackByMonth(index, item) {
    return item.getTime();
}

Has anyone an idea how I can avoid the redrawing of the DIV-Elements?

*ngFor with trackby , only refresh or add item when item in your array get changed or added or deleted, it doesn based on trackBy function provided as input ,

So if you items keep changing then its not going to help you, so Please check your items not modifying and keep object Identity instead of variable value like time.

to find out more you can make use of developer tool where after each modification in your dom your dom element get highlighted.

Example :

you need to have code as below where items having identifier , to track item and mostly when you add item or modify item then trackby functioon will come in picture and identify each object by its id value

 episodes = [
    { title: 'Winter Is Coming', director: 'Tim Van Patten', id: 0 },
    { title: 'The Kingsroad', director: 'Tim Van Patten', id: 1 },
  ];

  *ngFor="let episode of episodes;trackBy: trackById"

    trackById(index: number, episode: any): number {
    return episode.id;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM