Sometimes, we want to iterate over object in Angular.
In this article, we’ll look at how to iterate over object in Angular.
How to iterate over object in Angular?
To iterate over object in Angular, we can use the keyvalue
pipe.
For instance, we write
<div *ngFor="let item of myObject | keyvalue">
Key: <b>{{ item.key }}</b> and Value: <b>{{ item.value }}</b>
</div>
to loop through the entries in myObject
by using the keyvalue
pipe with *ngFor
.
Then we get the key’s value from item.key
and the value’s value with item.value
.
We can also add a function to sort the keys before we do the iteration.
For instance, we write
<div *ngFor="let item of myObject | keyvalue: sortKeys">
Key: <b>{{ item.key }}</b> and Value: <b>{{ item.value }}</b>
</div>
to sort the keys with sortKeys
before we iterate.
In our component class, we define it with
sortKeys = (a, b) => {
return a.key > b.key ? -1 : 1;
};
Conclusion
To iterate over object in Angular, we can use the keyvalue
pipe.