Error if don't check if {{object.field}} exists

VariablesPropertiesNullAngular

Variables Problem Overview


I have a question about checking if some field in object exists.

I want to print all categories which user has so I'm doing something like this:

  <ul *ngIf="user.categories.length >  0" *ngFor="#category of user.categories">
    <li>
      {{category.name}}
    </li>
  </ul>

The reason? All the data are PROPERLY printed, but I'm getting an error in web console like this:

Cannot read property 'name' of null

But when I do something like:

  <ul *ngIf="user.categories.length >  0" *ngFor="#category of user.categories">
    <li *ngIf="category">
      {{category.name}}
    </li>
  </ul>

Then all is okay.

Am I doing something wrong or maybe I have to check this every time? Have you ever had a problem like this one?

Variables Solutions


Solution 1 - Variables

basic usage

Use the safe-navigation operator

{{category?.name}}

then name is only read when category is not null.

array

This only works for the . (dereference) operator. For an array you can use

{{records && records[0]}}

See also https://stackoverflow.com/questions/38423276/angular-2-cannot-read-property-0-of-undefined-error-with-context-error-conte/38423299#38423299

async pipe

With async pipe it can be used like

{{(chapters | async)?.length

ngModel

With ngModel currently it needs to be split into

[ngModel]="details?.firstname" (ngModelChange)="details.firstname = $event"

See also https://stackoverflow.com/questions/39080980/data-is-not-appending-to-template-in-angular2/39081182#39081182

*ngIf

An alternative is always to wrap the part of the view with *ngIf="data" to prevent the part being rendered at all before the data is available to prevent the dereference error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionelzoyView Question on Stackoverflow
Solution 1 - VariablesGünter ZöchbauerView Answer on Stackoverflow