【发布时间】:2020-07-20 15:22:27
【问题描述】:
我使用这段代码来创建我的表单:
@Input() fetchedTask: Task;
taskForm: FormGroup;
formThresholds: FormArray;
this.taskForm = this._formBuilder.group({
taskId: null,
groupId: this.groupId,
name: ["", [Validators.required]],
taskType: this.taskTypeId,
etc.
configuration: this._formBuilder.group({
name: ["", Validators.required],
path: ["", Validators.required],
thresholds: this._formBuilder.array([])
})
});
我稍后使用setValue() 设置表单的值:
this.taskForm.controls["taskId"].setValue(this.fetchedTask.taskId);
我使用以下方法设置 FormArray 的值:
this.fetchedTask.configuration.thresholds.forEach((x)=>{
this.addItem(x.value, x.name);
})
addItem(value: number, name: string): void {
this.formThresholds = this.taskForm.get('configuration.thresholds') as FormArray;
this.formThresholds.push(this.createItem(value, name));
}
createItem(value: number, name: string): FormGroup{
return this._formBuilder.group({
value: value,
name: name
});
}
我真的不知道如何循环遍历我的数组值并在我的表单中显示它们,并使用填充的值。
我试过了,但没有成功:
<div *ngFor="let threshold of taskForm.get('configuration.thresholds') let i = index;">
<div [formGroupName]="i">
<input formControlName="name" placeholder="Threshold name">
<input formControlName="value" placeholder="Threshold value">
</div>
</div>
【问题讨论】:
-
试试这个taskForm['controls'].configuration.thresholds['controls']
-
@GouravGarg 我在尝试您的建议时收到此错误:“AbstractControl”类型上不存在属性“阈值”。
-
你可以试试这个吗? taskForm['controls'].configuration['controls'].thresholds['controls'] 或者您可以简单地创建一个 get 属性,如 get formArray():FormArray{return this.taskForm.get('configuration.thresholds') as FormArray;}
标签: angular forms formbuilder formarray