Search code examples
javascriptangularangular2-templateangular2-formsangular-ngmodel

Binding to an array of objects inside an ngFor, binds all inputs together


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}}

Solution

  • 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