我需要为表单动态创建 textarea
。我有以下模型:
this.fields = {
isRequired: true,
type: {
options: [
{
label: 'Option 1',
value: '1'
},
{
label: 'Option 2',
value: '2'
}
]
}
};
和形式:
this.userForm = this.fb.group({
isRequired: [this.fields.isRequired, Validators.required],
//... here a lot of other controls
type: this.fb.group({
options: this.fb.array(this.fields.type.options),
})
});
部分模板:
<div formGroupName="type">
<div formArrayName="options">
<div *ngFor="let option of userForm.controls.type.controls.options.controls; let i=index">
<textarea [formControlName]="i"></textarea>
</div>
</div>
</div>
因此,如您所见,我有一个对象数组,我想使用 label
属性将其显示在 textarea
中。现在我看到了 [object Object]
。如果我将 options
更改为一个简单的字符串数组,例如:['Option 1', 'Option 2']
,那么一切正常。但是我需要使用对象。所以,而不是:
<textarea [formControlName]="i"></textarea>
我试过:
<textarea [formControlName]="option[i].label"></textarea>
但是,它不起作用。
如何使用对象数组?
这是 Plunkr
最佳答案
您需要添加一个 FormGroup,其中包含您的 label
和 value
。这也意味着由表单创建的对象与您的 fields
对象具有相同的构建。
ngOnInit() {
// build form
this.userForm = this.fb.group({
type: this.fb.group({
options: this.fb.array([]) // create empty form array
})
});
// patch the values from your object
this.patch();
}
之后,我们使用在您的 OnInit 中调用的方法修补该值:
patch() {
const control = <FormArray>this.userForm.get('type.options');
this.fields.type.options.forEach(x => {
control.push(this.patchValues(x.label, x.value))
});
}
// assign the values
patchValues(label, value) {
return this.fb.group({
label: [label],
value: [value]
})
}
最后,这是一个
Demo
关于forms - 如何在响应式表单中使用对象数组作为控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42968619/