Reputation: 228
I'm trying to create a list of inputs with dynamic model but unfortunately, I get stuck on how I can implement this properly.
Basically, I have sample .ts
here. array of object has initial object which is the apple.
fruits: any[] = [
{
name1: 'Apple'
}
]
In my UI, I created something like this one:
<div *ngFor="let fruit of fruits; let i = index">
<input type="text" [(ngModel)]="fruit.name[i]" />
</div>
<button (click)="addNewInput()">Add new fruit</button>
When the user clicks the addNewInput()
button, then it should automatically add a new input.
But I'm getting an error that says, 0 is undefined
any help for this or alternative way to do this?
Here is the StackBlitz link: https://stackblitz.com/edit/angular-ivy-tbkzjw?file=src%2Fapp%2Fapp.component.html
Upvotes: 1
Views: 3738
Reputation: 1861
You are trying to access fruits['name'][0] -> this is not the same as fruits['name0'].
Given you are using *ngFor you shouldn't need to use the index position as well.
fruits: any[] = [
{ name: 'Apple' },
{ name: 'Pear' }
]
<div *ngFor="let fruit of fruits; let i = index">
<input type="text" [name]="'fruit' + i" [(ngModel)]="fruit.name" />
</div>
<button (click)="addNewInput()">Add new fruit</button>
You will have to add a name that is different for each input though, i have used the index for this purpose.
Upvotes: 2