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 to manage undefined value inside ngIf with condition as value?

I have a page in which I display a list of products contained inside an order, and a button to add more products. I must keep this structure, which is working perfectly fine when I’m opening an existing order. However, when I’m trying to create a new order, the condition inside the ngIf is undefined, and so the check fails.

What’s the best way to handle such a case, to make it so that the definition of the value products never fails or is there a better way to do it? In any case, how can I make it so that even if the order doesn’t have products (or they’re undefined), the div gets shown anyway?

<div
  *ngIf="
    order
      | map: 'product'
      | products
      | ngrxPush as products
  "
>
<!-- Order info -->
</div>

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

>Solution :

Simply use the safe navigation operator ? in condition; it will handle an undefined value.

<div *ngIf="(order?.products || []) | products | ngrxPush as products">
  <!-- Order info -->
</div>
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