具有递归模板的Angular ReactiveForm无法识别父formGroup指令

时间:2019-11-02 17:53:57

标签: angular angular-forms

在我的应用中,我是从一个看起来像这样的配置对象动态构建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会干扰吗?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:由于ng-template还不够,因为formControlName有点搞乱了模板中的层次结构。因此,必须像这样提供ng-template内部formControl的路径:

formGroup