How to iterate array using ngFor loop in angular

Viewed 67
'arr: { a: string[];b: string[];c: {id: number; name: string; }[]; } '

'''arr= {
a: ['rose', 'kelly', '35'],
b: ['marry', 'hadden', '40'],
c:[
{ id: 1, name: "Mark" },
{ id: 2, name: "John" },
{ id: 3, name: "Franc" },
{ id: 4, name: "Andrew " }
]
}

How to iterate above array using *ngFor loop in Angular'''

1 Answers

*ngFor directive expects the Array object to loop over. That's why you're receiving an error.

You can use keyvalue pair pipe to loop over this object, basically that will convert an object to an array, which would have key and value in separate object properties.

Since strictTemplate checking, typescript is throwing an error. To fix/suppress that error you can use define type of arr: {[key: string]: any}.

TS

arr: {[key: string]: any} = {
  a: ...,
  b: ...,
}

HTML

<div *ngFor="let item of arr | keyvalue">
  <b>{{ item.key }}</b>

  <div *ngFor="let val of item.value">
    {{ val.name ?? val }}
  </div>
</div>

Stackblitz

Related