如何使用反应形式编辑对象?假设我们有一个对象数组:
people = [
{name: "Janek", color:"blue", id: 1},
{name: "Maciek", color:"red", id: 2},
{name: "Ala", color:"blue", id: 3},
]
如果我想使用“模板驱动”方法来编辑对象的属性-这非常容易。 HTML
*ngFor="let person of people"
和
ngModel="person.name"
加上"person.color"
如何使用反应式表单执行此操作,以免丢失ID(和其他属性)?
答案 0 :(得分:2)
尝试一下:
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);
}
}
在您的模板中:
<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>
这是您推荐的Working Sample StackBlitz。