Reputation: 3181
How do I edit an object with reactive forms? Lets' assume we have an array of objects :
people = [
{name: "Janek", color:"blue", id: 1},
{name: "Maciek", color:"red", id: 2},
{name: "Ala", color:"blue", id: 3},
]
If I want to edit object's properties with Template Driven approach - it's farily easy. HTML
*ngFor="let person of people"
and
ngModel="person.name"
plus "person.color"
How to do this with Reactive Forms, so that I don't loose Id (and other properties)?
Upvotes: 1
Views: 5420
Reputation: 39432
Give this a try:
import { Component } from '@angular/core';
import { FormBuilder, FormArray, Validators, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
people = [
{ name: "Janek", color: "blue", id: 1 },
{ name: "Maciek", color: "red", id: 2 },
{ name: "Ala", color: "blue", id: 3 },
];
peopleForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.peopleForm = this.fb.group({
people: this.fb.array(this.people.map(person => this.fb.group({
name: this.fb.control(person.name),
color: this.fb.control(person.color),
id: this.fb.control(person.id)
})))
});
}
get peopleArray() {
return (<FormArray>this.peopleForm.get('people'));
}
onSubmit() {
console.log(this.peopleForm.value);
}
}
And in your Template:
<form [formGroup]="peopleForm">
<div formArrayName="people">
<div *ngFor="let person of peopleArray.controls; let i = index;">
<div [formGroupName]="i">
<input type="text" formControlName="name">
<input type="text" formControlName="color">
<input type="text" formControlName="id">
</div>
</div>
</div>
<button type="submit" (click)="onSubmit()">Submit</button>
</form>
Here's a Working Sample StackBlitz for your ref.
Upvotes: 5