1

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

Component.ts

instrumentsData = {
  particulars: ''
}

addParticular() {
  this.particulars.push('');
}

Component.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">
       <li>
           <input type="text" name="name" [(ngModel)]="instrumentsData.particular">
       </li>
   </ul>
</div>

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.