在我的应用中,我是从一个看起来像这样的配置对象动态构建formGroups
的:
const formElements: FormElementInterface[] = [
{
type: 'formControl',
defaultIsArray: false,
defaultValue: 'Apfel',
formControlName: 'fruits',
htmlTag: 'mat-input',
inputIype: 'text'
} as InputFormControlInterface,
];
FormElementInterface[]
由formControl
个对象或formGroup
个对象组成。后者可以包含formControls
或更多formGroups
。
构建实际的formGroup
(在模板中将看到completeForm
的过程很顺利),但是在模板内部遇到了一些问题并出现了此错误:
formControlName必须与父formGroup指令一起使用。您需要添加一个formGroup指令并将其传递给现有的FormGroup实例(可以在您的类中创建一个实例)
这是我的模板的摘录:
<form [formGroup]="completeForm">
<div *ngFor="let formElement of forms">
<ng-container
*ngTemplateOutlet="formElement.type === 'formGroup' ? formGroup : formControl; context:{$implicit: formElement}">
</ng-container>
</div>
</form>
<ng-template #formControl let-formElement>
<span [ngSwitch]="formElement.htmlTag">
<div *ngSwitchCase="'mat-input'">
<mat-form-field class="example-full-width">
<input matInput [value]="formElement.defaultValue" formControlName="fruits">
</mat-form-field>
</div>
</span>
</ng-template>
您会看到formGroup
已设置。 ng-template
会干扰吗?
答案 0 :(得分:1)
我找到了解决方案:由于ng-template
还不够,因为formControlName
有点搞乱了模板中的层次结构。因此,必须像这样提供ng-template
内部formControl
的路径:
formGroup