*ngFor object attribute undefined

I’m starting on Angular 2 coming from Angular 1, and I can’t figure how to use ngFor on an object’s attribute.
this.myVar is defined upon the result of an HTTP request, which defines the attr attribute.

Here’s my code:

# my_page.ts
import {Page} from 'ionic-angular';
import {MyService} from '../../services/my_service';

  templateUrl: 'build/pages/my_page/my_page.html',
  providers: [MyService]

export class MyPage {
  public myVar;

  constructor(private myService: MyService) {
      data => this.myVar = data

# my_page.html
<div *ngFor="#item of myVar.attr">

And this is the error:

EXCEPTION: TypeError: Cannot read property ‘attr’ of undefined in [myVar.attr in …]

Thank you!

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

Because initially till ajax gets completed myVar doesn’t have any value in it & while evaluating expression of ngFor, it tries to access attr property of undefined object. Do use [Elvis operator][1], by having ? it will check if object defined, if it is defined then then only it evaluate attr property from it.

<div *ngFor="let item of myVar?.attr"></div>