错误 TS2531:对象可能为“null”。在表单数组控件上

error TS2531: Object is possibly 'null'. on form array control

提问人:A. Gladkiy 提问时间:11/6/2023 更新时间:11/6/2023 访问量:48

问:

我有带有反应式表单数组项的模板:

<li class="nav-main-item" formArrayName="closedStatuses" *ngFor="let item of statusesForm.get('closedStatuses')['controls']; let i = index">
    <a formGroupName="{{i}}" class="nav-main-link" href="javascript:void(0)">
      <span class="nav-main-link-name">
        <div class="form-check">
          <input class="form-check-input"
                type="checkbox"
                [attr.id]="'closed-' + i"
                [attr.name]="'closed-' + i"
                formControlName="checked"
                (change)="onSelectStatus()">
          <label class="form-check-label" [attr.for]="'closed-' + i">{{ item.controls.name.value }}</label>
        </div>
      </span>
    </a>
</li>

我有错误:error TS2531: Object is possibly 'null'. statusesForm.get('closedStatuses')['controls']

如何修复此错误?

角度 反应形式

评论

0赞 Ada 11/6/2023
如果你像这样尝试会发生什么?statusesForm.get('closedStatuses')?.controls
0赞 A. Gladkiy 11/6/2023
@Ada然后我就出错了Property 'controls' does not exist on type 'AbstractControl<any, any>'.
0赞 Ada 11/6/2023
如果您将其显式转换为 FormArray,它是否有效?(statusesForm.get('closedStatuses') as FormArray)?.controls
0赞 A. Gladkiy 11/6/2023
@Ada 不,我认为在html模板中是未知的。error NG5002: Parser Error: Missing expected )FormaArray

答:

2赞 Ada 11/6/2023 #1

也许您可以使用辅助函数来获取数组?

getStatusControls() {
  const closedStatuses = this.statusesForm.get('closedStatuses');
  return closedStatuses ? closedStatuses['controls'] : [];
}

return 语句中的三元运算符应确保您永远不会尝试访问 。'controls'null

<li class="nav-main-item" formArrayName="closedStatuses" *ngFor="let item of getStatusControls(); let i = index">