KeyValue
pipe is an Angular built-in feature that transforms objects or maps into an array of key-value pairs.
If you've been working with Angular since its early versions, you might have missed it as the KeyValue
pipe was introduced in Angular 6.1.
Let's see it in action 🔥
Imagine a simple object that stores student's names as a key and an array of grades as a value.
const students = {
Susane: [4, 3, 2, 1, 5],
Jenifer: [3, 5, 2, 2],
John: [5, 3, 3, 4, 1]
};
With KeyValuePipe
you can iterate over objects directly from the template.
<ul *ngFor="let student of (students | keyvalue)">
<li>{{ student.key }}'s grades: {{ student.value }}</li>
</ul>
It is a clean and declarative solution that will allow you to clean up your templates.
Hope you're having a great one, and I'll see you for more 60 Seconds of Angular posts in the future 🥳
Top comments (4)
Useful thanks!
Nice tutorial, I like to store data in an object which allow for example to group a list. But an object is not easily iterable in an angular template. This pipe make this easy.
great read!
Thank you so much for this one! It's exactly the kind of explanation I've been looking for when it comes to this specific pipe. Keep up with the great work!