Search code examples
angularangular-reactive-forms

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


I have template with reactive form array item:

<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>

And I have error: error TS2531: Object is possibly 'null'. statusesForm.get('closedStatuses')['controls']

How can I fix this error?


Solution

  • Maybe you could use a helper function to get the array?

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

    The ternary operator in the return statement should ensure that you're never trying to access 'controls' of null.

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