Issue
I'm following the Angular 17 guide on dynamic forms. In this code snippet, they show how to loop using ngFor
to dynamically display an array of form controls.
<div formArrayName="aliases">
<h2>Aliases</h2>
<button type="button" (click)="addAlias()">+ Add another alias</button>
<div *ngFor="let alias of aliases.controls; let i=index">
<!-- The repeated alias template -->
<label for="alias-{{ i }}">Alias:</label>
<input id="alias-{{ i }}" type="text" [formControlName]="i">
</div>
</div>
How can I use the new @for
loop syntax introduced in Angular 17 here instead? I tried the following:
<div formArrayName="aliases">
<h2>Aliases</h2>
<button type="button" (click)="addAlias()">+ Add another alias</button>
@for (alias of aliases.controls; track $index; let i = $index;) {
<div>
<!-- The repeated alias template -->
<label for="alias-{{ i }}">Alias:</label>
<input id="alias-{{ i }}" type="text" [formControlName]="i">
</div>
}
</div>
But I get the error that Property $index does not exist on ...
I was expecting the for loop syntax I used to produce the same results as the example shown which uses ngFor.
Solution
There is an issue with the aliasing where let i = $index;
earases the $index
so it doesn't work on track:
You can fix it this way:
@for (alias of aliases.controls; let i =$index; track i; ) {
<div>
<!-- The repeated alias template -->
<label for="alias-{{ i }}">Alias:</label>
<input id="alias-{{ i }}" type="text" [formControlName]="i">
</div>
}
Or even better, you don't even need the alias anymore, you can directly use the implicit $index
in the template
@for (alias of aliases.controls; track $index) {
<div>
<!-- The repeated alias template -->
<label for="alias-{{ $index }}">Alias:</label>
<input id="alias-{{ $index }}" type="text" [formControlName]="$index">
</div>
}
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.