我想弄清楚数组中嵌套对象的形式。我已经阅读了几个问题和帖子,但我仍然无法弄清楚。也许我只是想念一件非常简单的事情。Angular 2在阵列中嵌套的Ojects
请参阅下面的简化代码。
HTML
<form [formGroup]="userForm" (ngSubmit)="submit(userForm.value)">
<hr>
<div formGroupName="type">
<div formArrayName="options">
<div *ngFor="let child of userForm.controls.type.controls.options.controls; let i = index" >
<div formGroupName="{{i}}">
<label>{{i+1}}. Test: </label>
<input formControlName="test" /><br>
<label>{{i+1}}. Label: </label>
<input formControlName="label" /><br>
<label>{{i+1}}. Value: </label>
<input formControlName="value" />
</div>
</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
<br>
<pre>{{userForm.value | json }}</pre>
应用
export class App {
name:string;
userForm: FormGroup;
fields: any;
ngOnInit() {
this.fields = {
isRequired: true,
type: {
options: [
{
test {
name: 'test1'
}
label: 'Option 1',
value: '1',
},
{
test {
name: 'test2'
}
label: 'Option 2',
value: '2'
}
]
}
};
this.userForm = this.fb.group({
type: this.fb.group({
options: this.fb.array([])
})
});
this.patch()
}
submit(value) {
console.log(value);
}
constructor(private fb: FormBuilder) { }
patch() {
const control = <FormArray>this.userForm.controls.type.controls['options'];
this.fields.type.options.forEach(x => {
control.push(this.patchValues(x.label, x.value))
})
}
patchValues(label, value) {
return this.fb.group({
test: {name: "HELP"},
label: [label],
value: [value]
})
}
}
我看起来就像这样......
1. Test: [object Object]
1. Label: Option 1
1. Value: 1
2. Test: [object Object]
2. Label: Option 2
2. Value: 2
[Submit]
和数据对象是
{
"type": {
"options": [
{
"test": {
"name": "HELP"
},
"label": "Option 1",
"value": "1"
},
{
"test": {
"name": "HELP"
},
"label": "Option 2",
"value": "2"
}
]
}
}
我正在寻找更改html模板以显示test.name而不是测试对象。我是否正确地初始化表单,或者我是否从HTML代码中错误地调用了该字段?当我将formControlName =“test”更改为formControlName =“test.name”时,它错误地指出test.name不存在。
所需的输出...
1. Test: HELP
1. Label: Option 1
1. Value: 1
2. Test: HELP
2. Label: Option 2
2. Value: 2