I have Json Object like
var obj = {
"TimSays":"I can Walk",
"RyanSays":"I can sing",
"MaxSays":"I can dance",
"SuperSays":"I can do it all"
}
I want to iterate this object in the template so i am using pipe help as there is no direct way to iterate obj in template in Angular2/4
import { Injectable, Pipe } from '@angular/core';
@Pipe({
name: 'keyobject'
})
@Injectable()
export class Keyobject {
transform(value, args:string[]):any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}}
Template Code
<div *ngFor="let o of obj | keyobject">{{o.value}}{{o.key}}</div>
In my Javascript if I am making any changes to the Json object dynamic changes are not getting reflected on the template.
obj.TimSays = "i want to sleep";
In template it still says i can walk. What i need to do here in case so template and ngFOr(Object) works like two way binding.
In angular pipes are pure by default, this means that they only run if there's a pure change to it's input.
If you want that your pipe is running on every change detection cycle you have to make in impure like this:
But keep in mind this can have a significant impact on your performance.
It would be better to perform a "pure" change to the input by creating a new reference when modifing your object, for example by using
Object.assign
:You can find more details about impure/pure pipes in the docs.