How to use TrackBy in ngFor in Angular?

2

Hello, I have a repeat structure where a pipe filter can be applied. I have read that trackBy can aid performance because it does not render the DOM unnecessarily.

I put it in my component:

trackByFn(index, item) {    
    return item.id; //Aplicado trackbyfn para melhorar performance do *ngFor
}

In my template:

<tr *ngFor="let calculo of calculos;let m = index; trackBy: trackByFn" class="table-line">

Am I doing it correctly? Do you have to pass some specific value to the trackby or just pass the function is enough?

    
asked by anonymous 04.10.2018 / 21:26

1 answer

3

Passing a function to trackBy is enough.

What you are doing is to tell Angular a unique ID for each rendering element of your array, so adding or removing an element will not render the entire tree again.

I hope I have helped.

    
05.10.2018 / 05:15