#@for and track

17 messages · Page 1 of 1 (latest)

urban dock
#

Hi,

Can anyone describe what the 'track' property in a @for block technical exactly do?
What happens in this example when my list items has the following structure?

[
  { label: 'Label 1', value:'label1' },
  { label: 'Label 2', value:'label2' }
]

@for (item of items; track item)

In my mind this is not a good idea because item is not an unique identifier, right?
What would be the best solution for this example?

gray bough
#

In this case @for will consider an element changed in the array only when its reference changes.
It should be like the old *ngFor behaviour, when no trackBy function was passed.
If you mutate a property of one of those object, without reassigning it, the DOM would not be updated.

urban dock
#

Ok ... this is also what I understand for this problem.
But what would be a good solution for a unique identifier if I not have a related ID etc?

gray bough
#

I suppose that label property would be unique.

urban dock
#

But is this enough? What is when the list will rendered 2 times on same page?
Then the identifier would be not more unique ... right?

gray bough
#

The identifier is part of the model.
You want both list rendering the same objects.

urban dock
#

For this example yes. I like to understand the behavior in general.
I understand, that in my example above I could use this, right?

@for (item of items; track item.label)

But how safe is this solution really?

#

What happens if I try to render the exact same list 2 times on a page?

gray bough
#

Why it should be a problem?

#

track is reading a value from the objects, not writing anything to them.
How could it be an issue?

still plover
#

if the array is static/never changes, you can go with track item.

#

just keep in mind that track item is a perf footgun if you use immutable data (=every change results in a changed reference)

signal stirrup
still plover
#

Yeah

signal stirrup
#

Thanks Matt 🙌

hallow prawn