Using template driven form with dynamic input list (ngFor)

帅比萌擦擦* 提交于 2019-11-29 21:12:45

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/39672719/using-template-driven-form-with-dynamic-input-list-ngfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!