Back to Tips

KeyValuePipe

Angular provides the keyvalue pipe, which transforms an Object or Map into an array of key value pairs. With it, an Object or a Map can be iterated by *ngFor.

@Component({
  selector: "keyvalue-pipe",
  template: `<span>
    <p>Object</p>
    <div *ngFor="let item of object | keyvalue">{{ item.key }}:{{ item.value }}</div>
    <p>Map</p>
    <div *ngFor="let item of map | keyvalue">{{ item.key }}:{{ item.value }}</div>
  </span>`,
})
export class KeyValuePipeComponent {
  object: { [key: number]: string } = { 2: "foo", 1: "bar" };
  map = new Map([
    [2, "foo"],
    [1, "bar"],
  ]);
}

Support

If you enjoyed this tip and found it useful, consider buying me a coffee. Thanks in advance!

Buy Me a Coffee at ko-fi.com
Using Angular v.19.0.3 🚀