我建议使用FormArray
这个。使用FormArray
,您的实现将如下所示:
对于组件类:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
export interface Data {
abbrev: string;
max: number;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
workForm: FormGroup;
workLeft: any[];
constructor(private fb: FormBuilder) {}
ngOnInit () {
this.workForm = this.fb.group({
points: this.fb.array([])
});
this.fillFormArray();
}
private fakeWebserviceCall(): Data[] {
return [
{ abbrev: 'foo', max: 12 },
{ abbrev: 'bar', max: 10 }
];
}
private fillFormArray() {
this.workLeft = this.fakeWebserviceCall();
const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
formControlsArray.forEach(control => this.points.push(control));
console.log(this.workForm.value);
}
get points(): FormArray {
return <FormArray>this.workForm.get('points');
}
pointAt(index) {
return (<FormArray>this.workForm.get('points')).at(index);
}
}
在模板中:
<form [formGroup]="workForm">
<div formArrayName="points">
<div *ngFor="let point of points.controls; let i = index">
{{ workLeft[i].abbrev }}: <input type="number" [formControlName]="i">
<div *ngIf="pointAt(i).invalid && (pointAt(i).dirty || pointAt(i).touched)">
The field is invalid
</div>
</div>
</div>
</form>
这是您参考的示例 StackBlitz。
PS:我对您分享的 StackBlitz 进行了一些更新,包括 Angular 样式指南推荐的内容以及实际解决方案。希望有帮助。