Why can't shows read the undefined property?

In my ionic-Angular app, I have loaded content from database and printed successfully to console, but I cannot communicate with the view, it says app.htmlMistake  

  <ion-card-content>
  {{homeContent.about}}
  </ion-card-content>

      

component.ts

constructor(public navCtrl: NavController, navParams: NavParams, public 
   homeService: HomeContentService, 
  public loadingCtrl: LoadingController) {
 this.homeService.geteventHomeContentForPage(this.event.id).subscribe(data=>
 { 
  this.homeContent=data;

  console.log(this.homeContent) 
  console.log(this.homeContent.about) 

 })
}

      

My console Output console

+3


source to share


1 answer


The problem is that the property is being homeContent

loaded async, so when Angular tries to render the view, homeContent

still undefined and then when trying to access the about

property. To fix this, use the elvis operator :

  <ion-card-content>
    {{ homeContent?.about }}
  </ion-card-content>

      

This will tell Angular not to try to read the property about

if homeContent

still null

/undefined


Some other ways to prevent this: add validation with the ngIf

following:



  <ion-card-content *ngIf="homeContent">
    {{ homeContent.about }}
  </ion-card-content>

      

In this case, we don't need the elvis (?) Operator, since the whole ion-card-content

will not be displayed if the property is homeContent

not defined.

Another possible way to avoid this error would be to initialize the property homeContent

as an object, so when trying to access its sub-properties, about

it will be null, but Angular will not throw an error:

public homeContent: any = {};

      

+5


source







All Articles