*ngFor object attribute undefined

10,656

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>
Share:
10,656
Lucas Moulin
Author by

Lucas Moulin

Updated on July 21, 2022

Comments

  • Lucas Moulin
    Lucas Moulin almost 2 years

    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!

  • Lucas Moulin
    Lucas Moulin about 8 years
    Thank you, this is exactly what I was looking for! Do you know if it's possible to use something like this for an Array position? Like myVar?[0]
  • Pankaj Parkar
    Pankaj Parkar about 8 years
    @akz92 you can do that.. but why you wanted to do it. as you each element of collection is being catch by ngFor
  • Lucas Moulin
    Lucas Moulin about 8 years
    I'm just curious :) I've never heard of this operator before