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