Angular2 *ngFor: “Cannot read property '0' of undefined”

前端 未结 3 1486
情歌与酒
情歌与酒 2021-01-05 19:06

I trying to get data from a JSON file to build a form.

Here is a portion of my template:

  
相关标签:
3条回答
  • 2021-01-05 19:43

    Alternative to @Gunter Zochbauer's solution, you can declare heroesas Array property of suitable type. If you have any class with all attributes of heroes you declare heroes property as:

    heroes:Array<Heroes> //Assuming class name is Heroes
    

    And initialize it in constructor as follows:

    constructor(){
    ...    
    this.heroes=new Array<Heroes>();
    }
    

    And in your ngFor loop simply access class attributes as follows:

    <option *ngFor="let p of heroes" [value]="p.place">{{p.place}}</option>
    

    Hope it helps.

    0 讨论(0)
  • 2021-01-05 19:51

    I figured out the problem. I got this error because I'm fetching data asynchronously and when Angular tries to resolve bindings the first time data is still null therefore heroes[0] fails.

    So I solved the problem initializing heroes array and using the "Elvis operator":

    heroes: Hero[]; instead of heroes: Hero[] = []; in the component.

    heroes[0]?.places instead of heroes[0].places in the html template.

    0 讨论(0)
  • 2021-01-05 20:04

    I guess what you want is

    *ngFor="let p of heroes?.data"
    

    because heroes seems to be an object, and ngFor can only iterate array. The level property also is in an array item.

    0 讨论(0)
提交回复
热议问题