*ngFor object attribute undefined

akz92 picture akz92 · Apr 12, 2016 · Viewed 9.2k times · Source

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';

@Page({
  templateUrl: 'build/pages/my_page/my_page.html',
  providers: [MyService]
})


export class MyPage {
  public myVar;

  constructor(private myService: MyService) {
    this.myService.fetch().subscribe(
      data => this.myVar = data
    );
  }
}

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

And this is the error:

EXCEPTION: TypeError: Cannot read property 'attr' of undefined in [myVar.attr in ...]

Thank you!

Answer

Pankaj Parkar picture Pankaj Parkar · Apr 12, 2016

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>