Friday, 10 November 2023

angular iterate over object with key and value

 https://stackoverflow.com/questions/31490713/iterate-over-object-in-angular

Angular 6.1.0+ Answer

Use the built-in keyvalue-pipe like this:

<div *ngFor="let item of myObject | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

or like this:

<div *ngFor="let item of myObject | keyvalue:mySortingFunction">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

where mySortingFunction is in your .ts file, for example:

mySortingFunction = (a, b) => {
  return a.key > b.key ? -1 : 1;
}
--------------------------------------------------------------------------
The above method might run into complier issues, because of --aot
if it does use :
https://stackoverflow.com/questions/45819123/how-to-loop-over-object-properties-with-ngfor-in-angular
<div *ngFor="let k of objectKeys(yourObject)">
    {{yourObject[k].color}}
</div>

and in the controller:

objectKeys(obj) {
    return Object.keys(obj);
}

No comments:

Post a Comment