引用 FormArray 中的 FormControl 元素



我似乎无法发现在我的组件模板中引用表单控件的方法。

虽然我正在将表单组(从 <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>

在此之后,页面继续,但以上是重要的。问题是引用"描述"是未定义的。

我尝试了以下参考:

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 迭代,但属性"无效"首先出现在说明中。

那么,如何引用这些控件及其值呢?

答案是:approval.get('description'(

我碰巧在一个不相关的帖子中偶然发现了对此的引用。这绝对是文档的一个很好的候选者,因为我不可能猜到这一点!

密钥在我的打字稿组件中。

  return this.fb.group({
    'description': ['', Validators.required],
    'approvalNumber': ['', Validators.required],
    'expires': new Date(),
  });

我实际上将三个控件放入一个组中,所以我正在迭代一个包含一个或多个 FormGroups 的 FormArray - 天哪!

不过有点奇怪的是,错误对象似乎不在同一路径上,因为:

approval.get('description').errors.required

返回"无法读取 null 的属性'必需'">

我花了大约 9 个小时!

最新更新