【发布时间】:2019-10-22 16:38:19
【问题描述】:
我必须创建具有验证功能的可重用动态表单。
我通过.ts 文件中的FormControl 属性值传递自定义表单模板结构,并在*ngFor 和ngSwitch 的帮助下构建表单。使用*ngFor 进入新的FormGroup。我有一个带有验证消息的div,并尝试使用*ngIf 和FormGroup 类'get 方法来切换可见性。
问题是我无法找出所需控件的路径。
<form [formGroup]="dynamicFilterFormGroup" (ngSubmit)="onSubmit()">
<div class="form-content">
<div class="form-row" *ngFor="let formRow of filterFormTemplate.formGroupArray" formGroupName="{{formRow.formGroupName}}">
<div class="form-element" *ngFor="let formElem of formRow.formControls">
<div [ngSwitch]="formElem.type">
<div *ngSwitchCase="'text'">
<div class="input-container">
<label>{{formElem.label}}</label>
<input type="text" formControlName="{{formElem.name}}" pInputText/>
<div class="form-validation-text" *ngIf="!dynamicFilterFormGroup.get(formRow.formGroupName.formElem.name).valid && dynamicFilterFormGroup.get(formRow.formGroupName.formElem.name).touched">{{ 'formElem.validationText' | lang }}</div>
</div>
</div>
<div *ngSwitchCase="'number'">
<div class="input-container">
<label>{{formElem.label}}</label>
<input type="number" formControlName="{{formElem.name}}" pInputText/>
</div>
</div>
...
...
...
</div>
</div>
</div>
<button class="form-element" pButton type="button" (click)="onSubmit()" label="{{ 'button_search' | lang}}"></button>
</div>
</form>
所以有问题的行是:
<div class="form-validation-text" *ngIf="!dynamicFilterFormGroup.get(formRow.formGroupName.formElem.name).valid && dynamicFilterFormGroup.get(formRow.formGroupName.formElem.name).touched">{{ 'formElem.validationText' | lang }}</div>
获取:
DynamicTableComponent.html:11 ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateDirectives] (DynamicTableComponent.html:11)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:45258)
at checkAndUpdateView (core.js:44270)
at callViewAction (core.js:44636)
at execEmbeddedViewsAction (core.js:44593)
at checkAndUpdateView (core.js:44271)
at callViewAction (core.js:44636)
at execEmbeddedViewsAction (core.js:44593)
at checkAndUpdateView (core.js:44271)
at callViewAction (core.js:44636)
提前感谢您的帮助!
【问题讨论】:
标签: angular angular-reactive-forms angular-validation