Using a form with a dynamic input list template (ngFor)

I am new to web development and working on a MEAN stack project using angular2. I am trying to add a form with a template with a dynamic input list using ngFor - however, I have observed abnormal behavior with the way I implement it. I am wondering if I am doing this correctly ...

Abnormal behavior: if I have to add 2 or more input fields and delete the entry for the latest entries, the next time I add new entries, it resets all entries below the one I just deleted. Also, are somehow new entries mandatory for the entries above?

problem demonstration

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

This is how I implement a dynamic input template form using ngFor. I meant another stackoverflow entry: angular -2-template-driven-form-with-ngfor-entries

<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. Thank you

+4
source share
1 answer

I like questions with a demo on Plunkr :)

I believe the problem is with your property name. This must be a unique name. Using an index as a unique value is incorrect. After changing the array, it will be mixed.

Therefore, I suggest you use idas a 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

+4
source

Source: https://habr.com/ru/post/1655679/


All Articles