Home > database >  Angular - How to fix an "Object is possibly 'null'" error from the component
Angular - How to fix an "Object is possibly 'null'" error from the component

Time:07-13

I am working on an e-commerce Angular 11 application.

I have a template that has to render an error message if the quantity provided for a cart item is less than 1.

The cartItem can be null (or undefined) and I can't (or am not allowed to) change that, since it comes like this from the back-end.

As a result, I get an

Object is possibly 'null' or 'undefined'.ngtsc(2533)

error.

I attempted to fix the problem in the template, this way:

<ng-container *ngIf="cartItem?.qty !== null && cartItem?.qty !== undefined">
    <app-alert *ngIf="cartItem?.qty < 1"
    type="error"
    [dismissible]='false'>
    You have to specify a quantity of at least one 
    </app-alert>
</ng-container>

I was expecting this to work, but it does not.

What is a viable solution to this problem?

CodePudding user response:

From here

<app-alert *ngIf="cartItem?.qty < 1"

The compiler will warn that cartItem is possibly null while you didn't handle the null or undefined case when comparing with the value (in the current element).

While you have done the null and undefined check (at the top level), you can remove the ? from cartItem.qty in <app-alert> element.

You can simplify as:

<ng-container *ngIf="cartItem?.qty">
    <app-alert *ngIf="cartItem.qty < 1"
    type="error"
    [dismissible]='false'>
    You have to specify a quantity of at least one 
    </app-alert>
</ng-container>

Or

<ng-container *ngIf="cartItem && cartItem.qty">
    <app-alert *ngIf="cartItem.qty < 1"
    type="error"
    [dismissible]='false'>
    You have to specify a quantity of at least one 
    </app-alert>
</ng-container>
  • Related