Angular 带有递归模板的 ReactiveForm 无法识别父 formGroup 指令
Angular ReactiveForm with recursive template doesn't recognize parent formGroup directive
在我的应用程序中,我从如下所示的配置对象动态构建 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 must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class)
这是我的模板的摘录:
<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
有干扰吗?
我找到了解决方案:由于 ng-template
formControlName
还不够,因为 ng-template
有点弄乱了模板中的层次结构。因此 formGroup
中 formControl
的路径必须像这样提供:
<input matInput [value]="formElement.defaultValue" [formControl]="getFormControl(formElement.formControlName)">
在我的应用程序中,我从如下所示的配置对象动态构建 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 must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class)
这是我的模板的摘录:
<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
有干扰吗?
我找到了解决方案:由于 ng-template
formControlName
还不够,因为 ng-template
有点弄乱了模板中的层次结构。因此 formGroup
中 formControl
的路径必须像这样提供:
<input matInput [value]="formElement.defaultValue" [formControl]="getFormControl(formElement.formControlName)">