我在* ngIf下有模板,它只在表单加载后生成。另外,我在动态显示的字段下有失败的表单,这取决于按下按钮。我注销表单,它返回正确缺少的FormControl。
模板:
<div *ngIf="ready">
<form [formGroup]="form">
<div [formGroup]="form.controls.request">
<div *ngFor="let field of inputFields">
...
</div>
</div>
<div *ngIf="somethingEnabled">
<div [formGroup]="form.controls.Something">
<div class="input-container">
<label>Name: </label>
<input formControlName="Name">
</div>
<div [formGroup]="form.controls.Something.Organization">
<div class="input-container">
<label>ASD: </label>
<input formControlName="ASD">
</div>
<div [formGroup]="form.controls.Something.Organization.Other">
<div class="input-container">
<label>Id: </label>
<input formControlName="Id">
</div>
<div [formGroup]="form.controls.Something.Organization.Other.SchmeNm">
<div class="input-container">
<label>SchmeName: </label>
<input formControlName="SchmeName">
</div>
<div class="input-container">
<label>SchmeValue: </label>
<input formControlName="SchmeValue">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
码:
generateForm() {
this.form = this.fb.group({
request: this.fb.group(
this.generateRequestFields())
,
Something: this.fb.group(this.generateSomething()),
address: this.fb.group(
this.generateAddress()
)
});
}
generateSomething() {
const returnObject = {};
returnObject['Name'] = new FormControl();
returnObject['Organization'] = this.fb.group(this.generateOrganization());
return returnObject;
}
generateOrganization() {
const returnObject = {};
returnObject['ASD'] = new FormControl();
returnObject['Other'] = this.fb.group({
Id: new FormControl(),
Schme: this.fb.group({
SchmeName: new FormControl(),
ShcmeValue: new FormControl()
}),
Issr: new FormControl()
});
return returnObject;
}
我只在激活form.controls.something部分时遇到错误。如果我删除模板的form.controls.Something.Organization部分,它工作正常。
错误:错误错误:formGroup需要一个FormGroup实例。请通过一个。
我可能刚刚错过了一些东西,并希望我会在发布这篇文章时找到它,但似乎仍然无法得到它
对于嵌套的formGroups,请使用formGroupName
而不是formGroup
。
当您在formGroup中时,您不需要访问父窗体的控件来定义它的子窗体组,您只需使用该名称
<form [formGroup]="form">
<div [formGroup]="request">
<div *ngFor="let field of inputFields">
...
</div>
可能如果你console.log(this.form.controls.Something.Organization)
它也将返回undefined。对于您添加的每个FormGroup,您必须先访问其控件,然后再转到下一级,如下所示:
<div [formGroup]="form.controls.Something.controls.Organization">
...
<div [formGroup]="form.controls.Something.controls.Organization.controls.Other">
...
试试吧。如果它不起作用(无法访问Something
),也可以尝试:
<div [formGroup]="form.get("Something").get("Organization")">
form.controls
将浏览您定义的确切路径,而form.get
将转到您指定的确切控件,使其对多层表单有用,便于维护和阅读。
让我们知道你得到了什么。