引用 FormArray 中的 FormControl 元素

Referencing FormControl elements in a FormArray

我似乎找不到在我的组件模板中引用表单控件的方法。

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

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

我试过以下参考:

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 迭代,但 属性 'invalid' 首先出现在描述中。

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

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

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

关键在我的打字稿组件中。

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

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

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

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

returns "Cannot read property 'required' of null"

我在这上面花了大约 9 个小时!