未嵌套对象时使用"formGroupName"



根据给定的声明对象,我有一个由许多字段自动生成的表单。formGroup也是动态生成的——一切都很好。

我遇到了嵌套对象的问题。我添加了formGroupName属性,并将其相应地设置为声明对象。如果字段未嵌套,则此属性值未定义。

我的问题是,当我添加formGroupName属性时,它被认为是嵌套的(无论我设置了什么值(,并且它正在FormGroup中搜索该值字段,并崩溃寻找非嵌套字段(找不到具有未指定名称属性的控件(。

有没有一种方法可以在嵌套和未嵌套时使用此属性(formGroupName(,将其值设置为将被视为未嵌套或忽略的值?

我试着写一个简短的代码来显示我的问题。

const declarations = [
{ name: 'id' },
{ name: 'id', parentName: "relatedObject" },
];
const formGroupMembers = {};
declarations.forEach(dec => {
if (dec.parentName){
formGroupMembers[dec.parentName] = this.formBuilder.group({[dec.name] : []});
}
else{
formGroupMembers[dec.name] = []
}
});
this.formBuilder.group(formGroupMembers);
<form [formGroup]="formGroup">
<mat-form-field *ngFor="let dec of declarations" formGroupName="{{dec.parentName}}">
<input matInput type="number" formControlName="{{dec.name}}">
</mat-form-field>
</form>

工作

由于我没有找到问题的解决方案,我用字段代码创建了一个子组件。但后来FormGroup&在父组件中声明的formGroupName。。在网上做了一些研究后,找到了解决这个问题的方法

这里是解决方案的片段。

这是包含字段组件的窗体/父组件

<form [formGroup]="formGroup">
<div *ngFor="let dec of declarations">
<div *ngIf="dec.parentName" [formGroupName]="dec.parentName">
<my-field [field]="dec"> </my-field>
</div>
<div *ngIf="!dec.parentName">
<my-field [field]="dec"> </my-field>
</div>
</div>
</form>

这是字段组件。

请注意,使字段组件成为父组件中表单组的一部分的viewProviders部分。正如这里所解释的。

import { Component, Input, SkipSelf } from '@angular/core';
import { ControlContainer } from '@angular/forms';
@Component({
selector: 'my-field',
templateUrl: './my-field.component.html',
styleUrls: ['./my-field.component.scss'],

/////////////////// THIS IS VERY IMPORTANT /////////////////
viewProviders: [ 
{
provide: ControlContainer,
useFactory: (container: ControlContainer) => container,
deps: [[new SkipSelf(), ControlContainer]]
}
]
/////////////////// THIS IS VERY IMPORTANT /////////////////
})
export class MyFieldComponent {
@Input() field: FieldDesc;
}
<input matInput type="number" [formControlName]="field.name" />

最新更新