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!
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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With