Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

@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!

like image 397
Lucas Moulin Avatar asked Apr 12 '16 20:04

Lucas Moulin


1 Answers

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>
like image 166
Pankaj Parkar Avatar answered Oct 12 '22 10:10

Pankaj Parkar