How to use Trackby in ngFor in Angular?

Asked

Viewed 264 times

2

Hello, I have a repeating structure where a pipe filter can be applied.I have read that trackBy can help 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? Have to pass some specific value to the trackby or just pass the function is enough?

1 answer

3


Passing a function to trackBy is enough.

What you are doing is informing Angular of a unique Id for each element rendering its array, so adding or removing some element will not render the complete tree again.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.