LAUTARO
LAUTARO

Reputation: 11

ngFor cannot read property of undefined

I have these interfaces

order.interface.ts

export interface Order {
    userName: string;
    food: Food[];
    description: string;
    totalPrice: number;
    deliveryAddress: string;
}

food.interface.ts

export interface Food {
    description: string;
    price?: number;
}

I create an array of objects to then go through it in html

 orders: Order[] = [
    {
      userName:  "Miguel",
      totalPrice: 90,
      description: "ice cream",
      deliveryAddress: "address",
      food: [
        {
          description: 'food1',
        },
        {
          description: 'food2',
        }
      ]
    }]
<ion-list ngFor="let item of order?.food;">
    <ion-item>
      {{item.description}}
    </ion-item>
</ion-list>

i get the following error:

Cannot read properties of undefined (reading 'description')

Upvotes: 0

Views: 139

Answers (1)

Jago
Jago

Reputation: 2935

At some point your item is being undefined thus not having a description attribute.

Try conditionally accessing attribute with ?.:

{{item?.description}}

Upvotes: 1

Related Questions