[英]Angular 6 Form Array cannot be accessed inside an ng-container
我有一個 ng-container 描述了我所有可能的表單字段模板,主要是根據字段的元數據在一個大的 switch 語句上:
<ng-template #dynamicFormField let-field="inputField">
<div *ngIf="field.dataTypeName == 'ShortText'">
<mat-form-field class="col-md-6">
<input matInput type="text" [placeholder]="field.attributeLabel" [formControlName]="field.attributeName">
</mat-form-field>
</div>
<div *ngIf="field.dataTypeName == 'LongText'">
<mat-form-field class="col-md-12">
<input matInput type="text" [placeholder]="field.attributeLabel" [formControlName]="field.attributeName">
</mat-form-field>
</div>
<div *ngIf="field.dataTypeName == 'Number'">
<mat-form-field>
<input matInput type="number" [placeholder]="field.attributeLabel" [formControlName]="field.attributeName">
</mat-form-field>
</div>
<ng-template>
我有一個基本的表單組,然后表單組的一個屬性是一個表單數組,其中的每個元素都有自己的表單組。 例如,數據模型如下所示:
{
name: 'Article Name',
description: 'Some description of the article',
sections: [
{
sectionName: 'Rich text section',
sectionContent: 'Some rich text'
},
{
sectionName: 'Second section',
sectionContent: 'Some rich text'
}
]
}
其中每個字段都有描述其表單屬性的相應元數據。
我希望能夠在基本表單組以及表單數組中的表單組中重用輸入 switch 語句。 但是ng-container內部無法訪問formarray的formGroupName輸入指定的formgroup:
<div *ngFor="let field of this.sectionTypeSchemas[section.value.sectionTypeId]">
<div *ngIf="field.isVisible != false" formGroupName="{{i}}">
<ng-container *ngTemplateOutlet="dynamicFormField;context:{ inputField:field }"></ng-container>
</div>
</div>
我遇到的錯誤基本上是 Angular 無法找到 formarray 的 FormGroups 內的控件(即數據模型中的 sectionName),盡管找到與基本表單組控件對應的控件(名稱和描述來自數據模型)。 有沒有辦法可以手動將表單組引用傳遞給 ng-container? 一個簡短的例子可以在這里看到。
首先,我可能會使用子組件而不是 ng-template,因為它也在上面的評論中建議。
盡管如此,為了讓您的示例工作,需要修復兩件事
每次在 ng-template 中使用 formGroup 的 formControl 時,如果 form-tag 放置在 ng-template 之外,則需要確保在 ng-template 中添加具有 formGroup 綁定的標簽。
在您的情況下,有一些特別之處,因為您的 ng-template 中的 formGroup 實際上是一個 subFormGroup - 每個 formArrayItem 的 formGroup
如果您要綁定到 formArray,您需要記住,您需要外部控件上的 formArrayName 以及與索引的綁定。 請看這里以獲得進一步的解釋: FormArray binding
你在 stackblitz 里面有一個錯字:secitonHeader 而不是 sectionHeader。
這是一個工作: stackblitz
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.