我似乎无法在组件模板中找到引用表单控件的方法。
虽然我将表单组(从<form>
标记)传递到此子组件,但我知道我有一个有效的FormGroup对象结构,因为我可以看到console.log的原始输出(this.f .getRawValue()):
abn:""
addressLine1:""
addressLine2:""
addressLine3:""
addressPostcode:""
addressState:""
addressSuburb:""
contactEmail:""
contactFax:""
contactMobile:""
contactPhone:""
fcApprovals:Array(1)
0:
approvalNumber:""
description:""
expires:Sat Mar 03 2018 17:07:50 GMT+1100 (AEDT) {}
这正是我期望进入html
形式的对象结构<div *ngIf="f.get('fcApprovals')" [formGroup]="f" class="block-container center form-panel not-full-width">
<div class="panel-title">Approvals</div>
<div class="block-container center not-full-width" formArrayName="fcApprovals"
*ngFor="let approval of f.get('fcApprovals').controls; let i = index;">
<div class="block-element pad-me-up" [formGroupName]="i">
<div class="form-group" [ngClass]="{
'has-danger': description.invalid && description.dirty,
'has-success': description.valid && description.dirty}">
<input type="text" class="form-control" placeholder="Description" name="description"
formControlName="description" required/>
<div *ngIf="description.untouched || description.valid"
class="ui message">Description
</div>
<div *ngIf="description.dirty || description.touched">
<div *ngIf="description.errors.required"
class="ui error message">Description is required
</div>
</div>
<div class="icon description"></div>
</div>
此后页面继续,但上述内容非常重要。问题是参考&#34;描述&#34;未定义。
我尝试过以下的评论:
i.description
approval.description
fcApprovals[i].description
fcApprovals[i].control.description
还有更多。似乎没什么用。我得到的错误是:
ApprovedComponent.html:6 ERROR TypeError: Cannot read property 'invalid' of undefined
at Object.eval [as updateDirectives] (ApprovedComponent.html:8)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14651)
at checkAndUpdateView (core.js:13798)
at callViewAction (core.js:14149)
at execEmbeddedViewsAction (core.js:14107)
at checkAndUpdateView (core.js:13799)
at callViewAction (core.js:14149)
at execEmbeddedViewsAction (core.js:14107)
at checkAndUpdateView (core.js:13799)
at callViewAction (core.js:14149)
错误引用了描述引用正上方的FormArray迭代,但该属性“无效”&#39;首先出现在描述中。
那么,您如何引用这些控件及其值?
答案 0 :(得分:0)
答案是: approval.get(&#39;说明&#39;)
我碰巧在一篇不相关的文章中偶然发现了对此的引用。它绝对是文档的一个很好的候选者,因为我无法猜到这一点!
关键是我的打字稿组件。
return this.fb.group({
'description': ['', Validators.required],
'approvalNumber': ['', Validators.required],
'expires': new Date(),
});
我实际上把三个控件放到一个组中,所以我正在迭代一个包含一个或多个FormGroup的FormArray - 很棒!
虽然有点奇怪,但似乎错误对象不在同一条路径上,因为:
approval.get('description').errors.required
返回&#34;无法读取属性&#39;要求&#39; of null&#34;
我已花了大约9个小时!