Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I fix an "Object is possibly 'null'" error from the component's template in Angular 11?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading