简体   繁体   中英

Angular Dynamic [*ngModel)] for List of Inputs

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM