Reputation: 160
In my code, if i click the add_box
icon, it will add another input form below so that I could input more values, but this is the problem shown in this link http://g.recordit.co/R0iifhd6Wd.gif
and this is my code
instrumentsData = {
particulars: ''
}
addParticular() {
this.particulars.push('');
}
<div class="form-group">
<button (click)="addParticular()" class="button-box"><i class="material-icons">add_box</i></button>
<ul class="form-fields" *ngFor="let particular of particulars">
<li>
<input type="text" name="name" [(ngModel)]="instrumentsData.particular">
</li>
</ul>
</div>
Upvotes: 1
Views: 2368
Reputation: 349
The reason why you get this issue is you always bind 1 value in ngModel instrumentsData.particular
You could resolve your issue by doing like this:
HTML:
<div class="form-group">
<button (click)="addParticular()" class="button-box"><i class="material-icons">add_box</i></button>
<ul class="form-fields" *ngFor="let particular of particulars; index as i;trackBy: trackByFn">
<li>
<input type="text" name="name" [(ngModel)]="particulars[i]">
</li>
</ul>
</div>
Component.ts:
...
particulars: any[] = [];
addParticular() {
this.particulars.push('');
}
trackByFn(index, item) {
return index;
}
...
Here is your plunker: https://plnkr.co/edit/98mLfBla5KQqx4hpNne2?p=preview
Or it could be another array then you don't need trackBy in *ngFor
Upvotes: 1
Reputation: 2487
the problem is simple. your are using the same ngModel for all your inputs, that's why you can see that behavior in your app
if particular is a array then you can do it like
<div class="form-group">
<button (click)="addParticular()" class="button-box"><i class="material-icons">add_box</i></button>
<ul class="form-fields" *ngFor="let particular of particulars; let i= index">
<li>
<input type="text" name="name" [(ngModel)]="instrumentsData.particular[i]">
</li>
</ul>
</div>
Upvotes: 0