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:
Contents
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.
Practice
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'; @Component({ 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
->
<h3>Object with Keyvalue pipe</h3> <div *ngFor="let item of object | keyvalue"> key: {{item.key}} - value: {{item.value}} </div> <h3>Map with Keyvalue pipe - Desc Order</h3> <div *ngFor="let item of map | keyvalue:desc"> key: {{item.key}} - value: {{item.value}} </div> |
-> Results:
Sourcecode
Project structure ->
SourceCode:
Last updated on March 21, 2019.
This is incredible, how structure and simple to follow are your tutorials….and for free! very well done
Very cool.
Trying to use ngModel to edit item.value – doesn’t seem to be working. Any ideas on making that work?