Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using template driven form with dynamic input list (ngFor)

I am new to web development and is working on a MEAN stack project using angular2. I am trying to add template-driven form with dynamic list of input using ngFor - however I did observe an abnormal behavior with the way I implement it. I am wondering if I am doing it the right way...

Abnormal behavior: If I were to add 2 or more input field and remove the non-last-entries input, the next time i add the new entries, it resets all the entries below the one I just deleted. In addition, somehow the new entries are binding with the entries above?

demo of the issue

Here is my plunker: http://plnkr.co/edit/FjLg8VDDo3E6fHVgS8ah?p=preview

Here is the way that I implement template driven form with dynamic input using ngFor. I was referring to another stackoverflow post:angular-2-template-driven-form-with-ngfor-inputs

<div *ngFor="let hero of heroArray; let i = index">

             <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name"
                   required
                   [(ngModel)]="hero.name" name="name-{{i}}"
                   #name="ngModel" >
            <div [hidden]="name.valid || name.pristine"
                 class="alert alert-danger">
              Name is required
            </div>
          </div>
      </div>

Any help is appreciated. Thanks!

like image 845
RunningBear Avatar asked Sep 24 '16 05:09

RunningBear


1 Answers

I like questions with the demonstration on the Plunkr:)

I suppose that the problem is related with your name property. It should be unique name. Using index as unique value is wrong. It will be mixed after changing your array.

So i offer you to use id as unique name:

let uniqueId = 1;
...
addNewHero(){
  var hero: Hero  = new Hero(uniqueId++,'','');
  this.heroArray.push(hero);
}

and in html:

<input type="text" ... name="name-{{hero.id}}">

Here is the Plunker

like image 156
yurzui Avatar answered Nov 15 '22 15:11

yurzui