I have the following angular template file that displays some team names, and I have this for
loop inside an if
directive:
@if (teams) {
<p>Teams not null</p>
@for (team of teams; track $index) {
<app-name-box [name]="team"></app-name-box>
}
}
This code is the template code for a component that I dynamically create multiple instances of, and is the only html code associated with the component. I assumed that anything inside the if
would not get rendered if the if
returns false. Only one of these components (the first one) has been given a value for teams
, the others are given null
, and I can see that because the “Teams not null” message only shows up in one of the instances of the component when dynamically duplicated. However, as I dynamically duplicate this component, I get the following error:
The provided track expression resulted in duplicated keys for a given collection. Adjust the tracking expression such that it uniquely identifies all the items in the collection. Duplicated keys were: key "" at index "0" and "1"
.
As I duplicate this component, key "" at index "1" and "2"
, key "" at index "2" and "3"
and so on are added to the list of duplicate keys, incrementing for every new instance created. I am struggling to understand why this is the case, since only one instance of this for loop should ever occur, so why are duplicate keys becoming a problem?
This does not seem to be a commonly reported issue, at least I have not been able to find much info about it so I had limited ideas as to how to try fix this. I did try using the *ngIf
and *ngFor
directives inside of the @
labelled ones but got the same result. I don’t know what else I can even try, as I am not particularly experienced in Angular.
I am using Angular version 18.0.3 if that is relevant.