What is KeyValue Pipe in Angular: Usage and Examples
KeyValuePipe in Angular transforms an object or a map into an array of key-value pairs, making it easy to iterate over them in templates. It helps display dynamic object properties in a readable list format.How It Works
The KeyValuePipe takes an object or a map and converts it into an array where each element is an object with key and value properties. This lets Angular templates loop over the keys and values easily using *ngFor.
Think of it like turning a dictionary into a list of cards, each card showing a word and its meaning. This way, you can display all entries without knowing the keys beforehand.
Angular sorts the keys by default in ascending order, but you can customize the sorting if needed.
Example
This example shows how to use the keyvalue pipe to display all properties of an object in a list.
import { Component } from '@angular/core'; @Component({ selector: 'app-keyvalue-example', template: ` <h3>User Info</h3> <ul> <li *ngFor="let item of user | keyvalue"> {{item.key}}: {{item.value}} </li> </ul> ` }) export class KeyValueExampleComponent { user = { name: 'Alice', age: 30, city: 'Wonderland' }; }
When to Use
Use the keyvalue pipe when you want to display or process all properties of an object or map in your Angular template. It is especially useful when the keys are dynamic or unknown ahead of time.
Common real-world uses include showing user settings, configuration options, or any data stored as key-value pairs where you want a simple list or table view.
Key Points
- The
keyvaluepipe converts objects/maps into arrays of key-value pairs. - It enables easy iteration over object properties in templates.
- Keys are sorted by default but sorting can be customized.
- Useful for displaying dynamic or unknown object keys.