I'm testing Angular's keyvalue
pipe with simple code:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div *ngFor="let prop of testObj | keyvalue">
<div>key: {{prop.key}}</div>
<div>value: {{prop.value}}<div>
</div> `
})
export class AppComponent {
testObj = { id: 1, name: "Abdul Rafay" }
}
but it's giving me this error:
Template parse errors: The pipe 'keyvalue' could not be found ("]prop of testObj | keyvalue"> key: {{prop.key}} value: {{prop.value}}"): ng:///AppModule/AppComponent.html@0:17 Evaluating src/main.ts Booting application
am i missing anything? Here's my Stackblitz
KeyValuePipelinkTransforms Object or Map into an array of key value pairs. {{ input_expression | keyvalue [ : compareFn ] }}
The KeyValue Pipe converts given Object or Map into an array of key-value pairs. We can use this with the ngFor to loop through the object keys. The keyValue accepts the one argument compareFn , which we can use to set the custom sort to the pipe.
KeyValue pipe released in Angular 6.1 to loop through objects,Maps and arrays. Now by passing KeyValue pipe to *ngFor we can loop through objects key values & maps. Prior to this Angular 6.1 release we cannot iterate directly through objects key values & maps using *ngFor directive.
The KeyValue Pipe is available in angular 6.1 to Update your dependencies it will work
If you are using angular 6 you can try this
HTML
<div *ngFor="let prop of key">
<div>key: {{prop}}</div>
<div>value: {{testObj[prop]}}<div>
</div>
TS
testObj = { id: 1, name: "Abdul Rafay" }
get key(){
return Object.keys(this.testObj);
}
Example: https://stackblitz.com/edit/angular-6-template-x9hady
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With