1

I'm trying to create a registration form for an array of persons with Angular. Persons are in an array of Person objects. The problem is that all input fields are bind together! I did this with a String[] and it works like a charm but when using Person class it misbehaves!

enter image description here

This is my component:

Stackblitz.com: https://stackblitz.com/edit/angular-m5xzds

TS file:

import { Component } from '@angular/core';

class Person {
  constructor(
    firstname: string,
    lastname: string) { }
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  array = Array;
  count = 3;
  persons: Person[];
  ngOnInit() {
    this.persons = new Array<Person>(5).fill({});
  }
}

Template:

count: <input type="number" name="count" [(ngModel)]="count">
<div>Persons:</div>

<div *ngFor="let item of array(count).fill(0); index as i">
  <form>
<input [(ngModel)]="persons[i].firstname" type="text" class="form-control" name="name_{{i}}">

  </form>
</div>
{{persons|json}}
rostamiani
  • 2,859
  • 7
  • 38
  • 74

2 Answers2

2

*ngFor can loop over your list of persons directly, i feel like you could simplify this by doing the following.

  <form>
<div *ngFor="let person of persons; let i = index">
<input *ngIf="i < count" [(ngModel)]="person.firstname" type="text" class="form-control" name="{{person.firstname}}">  
</div>
</form>
Sam
  • 1,736
  • 8
  • 15
1

the Array.fill method passes the reference so it's basically the same object in the five places of your persons array, it was working with string array because string are immutable and the array is full of 'different' strings. See this question.

So you can use a map function to solve that as in the question or separate the ngmodel and the ngmodelchange see example here: stackblitz example

captain hak
  • 742
  • 6
  • 20