Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 237
elzoy Avatar asked Jan 20 '16 21:01

elzoy


People also ask

How to check if a property is in an object JavaScript?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.

How do you check if a property exists in an object TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.

How do you check object is defined or not in JavaScript?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.


1 Answers

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 Angular 2 - Cannot read property '0' of undefined error with context ERROR CONTEXT: [object Object]

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 Data is not appending to template in angular2

*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.

like image 153
Günter Zöchbauer Avatar answered Oct 13 '22 10:10

Günter Zöchbauer