Angular 6 – KeyValue Pipe – *ngFor Loop through Object, Map example


Angular 6.1 provides a new KeyValue pipe transforms Object or Map into an array of key value pairs. In the tutorial, we will show you how to iterate through Object, Map with KeyValue pipe.

Related posts:
Angular 6 Service – with Observable Data for Asynchronous Operation
Angular 6 Routing/Navigation – with Angular Router Service
Angular 6 Template Driven Form – NgModel for Two-Way Data Binding

Related pages:

KeyValue Pipe

Transforms Object or Map into an array of key value pairs ->
{{ input_expression | keyvalue [ : compareFn ] }}

Input value

Input can be null, objects, or maps ->
null | { [key: string]: V; [key: number]: V; } | Map

Comparator Function

compareFn function is optional, used to sort the converted array based upon unicode point values of keys.

(a: KeyValue, b: KeyValue) => number

  • keys are numbers -> sorted by ascending order.
  • keys are strings -> sorted by alphabetical order.
  • key is undefined or null -> displayed at last.

Angular KeyValue pipe has defaultComparator function to sort the key value array.
We can re-implement a new compareFn if our keys are complex types.


We create an Angular keyvalue-pipe component that uses KeyValue pipe to iterate through an Object and Map ->

KeyValuePipe Component class

keyvalue-pipe.component.ts ->

import { Component, OnInit } from '@angular/core';

  selector: 'app-keyvalue-pipe',
  templateUrl: './keyvalue-pipe.component.html'
export class KeyvaluePipeComponent{

  constructor() { }

  object: { [key: number]: string } =
    1: 'Property 1',
    2: 'Property 2',
    3: 'Property 3'
  map = new Map([
    [4, 'Four'],
    [6, 'Six'],
    [5, 'Five'],
  desc = (a, b) => {
    if(a.key < b.key) return b.key;

KeyValuePipe style

keyvalue-pipe.component.html ->

code class="language-html"><h3>Object with Keyvalue pipe</h3>
<div *ngFor="let item of object | keyvalue">
    key: {{item.key}} - value: {{item.value}}
<h3>Map with Keyvalue pipe - Desc Order</h3>
<div *ngFor="let item of map | keyvalue:desc">
    key: {{item.key}} - value: {{item.value}}

-> Results:



Project structure ->




2 thoughts on “Angular 6 – KeyValue Pipe – *ngFor Loop through Object, Map example”

Leave a Reply

Your email address will not be published. Required fields are marked *