Cannot read property 'query' of null


#1

Hello, I am currently working on ionic 3 project. I am trying to repeat a list of objects in array using ngFor. However, some properties of some objects do not exist at all. i keep on getting TypeError: Cannot read property ‘query’ of null. Is there anyway to skip the propeties that do not exist on the object and still load the rest.

<ion-content >
  <ion-card *ngFor="let image of images">
    <img src="{{image.images.low_resolution.url}}">
    <ion-card-content>
    <!-- this property exist on some objects only -->
     <p > {{image.caption.text}}  </p>
  </ion-card-content>
  </ion-card>
</ion-content>

#2

Someone will probably suggest the Elvis operator, but I would instead use ngIf to make the DOM cleaner:

<p *ngIf="image.caption">{{image.caption.text}}</p>

#3

thanks @rapropos
i found the solution.

I added '?'  to 'caption' and it now works fine.

<p *ngIf="image.caption">{{image.caption?.text}}</p>

#4

Good Work @affulisaac

" ? " is used when we try to handle undefined value.


#5

As I said in my previous post, the Elvis operator (?.) is rendered unnecessary by the presence of the ngIf.