提问人:A. Gladkiy 提问时间:11/6/2023 更新时间:11/6/2023 访问量:48
错误 TS2531:对象可能为“null”。在表单数组控件上
error TS2531: Object is possibly 'null'. on form array control
问:
我有带有反应式表单数组项的模板:
<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']
如何修复此错误?
答:
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">
评论
statusesForm.get('closedStatuses')?.controls
Property 'controls' does not exist on type 'AbstractControl<any, any>'.
(statusesForm.get('closedStatuses') as FormArray)?.controls
error NG5002: Parser Error: Missing expected )
FormaArray