0

I am trying to access the category slug for a product in ionic using the WordPress rest API. This seems to work fine on one page as <h3 class="product-name uppercase">{{productdetail?.categories[0].slug}}</h3> however this does not seems to work when i try implementing the same using for loop in angular on another page

<div class="width50" *ngFor="let object of dataList">
    <img src="{{object.images[0].src}}" width="150"  (click)="navigateToPage(object.id)" />
    <h3 class="product-name uppercase" text-nowrap>{{object?.categories[0].slug}}</h3> 
</div>

it gives an error as v.context.$implicit.categories[0] is undefined however on same page the code for image source seems to work fine.

Ankur Bhadania
  • 4,123
  • 1
  • 23
  • 38
OshoParth
  • 1,492
  • 2
  • 20
  • 44
  • object?.categories?[0].slug – Milad Jul 06 '17 at 09:20
  • @Milad does not work generates "Template parse errors:Parser Error: Conditional expression object?.categories?[0].slug requires all 3 expressions at the end of the expression. – OshoParth Jul 06 '17 at 09:28
  • `object?.categories[0]?.slug` – yurzui Jul 06 '17 at 18:30
  • @yurzui Thanks that worked could you please answer the same and also please explain the concept of inserting "?" symbol. ? – OshoParth Jul 07 '17 at 04:12
  • Possible duplicate of [Ionic Error v.context.$implicit is undefined](https://stackoverflow.com/questions/47008316/ionic-error-v-context-implicit-is-undefined) – Félix Brunet May 22 '19 at 15:08

1 Answers1

1

According to the docs

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

This way if write

obj?.foo

angular will transform it to the following expression.

obj == null ? null : obj.foo

so if the obj is empty value then you won't see any of errors.

In your case you can use the expresion

object?.categories[0]?.slug

that will be transformed to

object == null ? null : object.categories[0] == null ? null : object.categories[0].slug;

Safe navigation operator is helpful if you don't know whether your object contains any value or not, or you load data asynchronously and your object is undefined at first time.

yurzui
  • 205,937
  • 32
  • 433
  • 399