Nix
Nix

Reputation: 58562

Angular 2 /Ionic 2 undefined property causes template to not refresh

I just got done trying to fix the below issue for 4 hours.

<ion-card *ngIf="user">
      <ion-item>
        <h2>{{user.FirstName}}!</h2>
        <p>{{user.Company.Name}}</p>
      </ion-item>
 </ion-card>
 <some-other-component></some-other-component>


user = {
    FirstName: 'Nick'
};

Notice that user.Company is not set. My entire component just stopped working. Not just the ion-card, some-other-component rendered once and then stopped updating. It was responding to click events, but never updating.

My Question is: is there any way to force Angular / Ionic to display that it failed to render versus just failing?

My fix was to: <p>{{user?.Company?.Name}}</p> it's scary to me that we are now going to have to check every object for property existence. I'm wondering if there is something I just need to set/configure in order to change how this behaves. Desired outcome is either a console error, or to just render like Angular 1.x did.

Upvotes: 3

Views: 548

Answers (2)

Manuel Taber
Manuel Taber

Reputation: 427

No, there is no setting to force the rendering on runtime errors. You have to check the assignment with '?' or bind to a method that checks internal the assignments.

Upvotes: 2

sebaferreras
sebaferreras

Reputation: 44669

Just one elvis operator (?) is needed in this case. Since you're including *ngIf="user" in the ion-card element, you just need to check if the Company property is not null like this:

<p>{{user.Company?.Name}}</p>

Upvotes: 1

Related Questions