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

angular-6-keyvalue-pipe-ngfor-loop-through-object-map-example-feature-image

Angular 6.1 provides a new KeyValue pipe transforms Object or Map into an array of key value pairs. In the tutorial, we will guide 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.

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 ->

KeyValuePipe style

keyvalue-pipe.component.html ->

-> Results:

angular-6-keyvalue-pipe-ngfor-loop-through-object-map-results

Sourcecode

Project structure ->

angular-6-keyvalue-pipe-ngfor-loop-through-object-map-angular-project-structure

SourceCode:

Angular6-KeyValue-Pipe

By grokonez | August 29, 2018.



Related Posts


Got Something To Say:

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

*