简体   繁体   中英

Angular2/4 How to update template in *ngFor is working on [object,object]?

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:

@Pipe({ 
  name: 'keyobject',
  pure: false
})

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 :

obj = Object.assign({}, obj, { TimSays: 'i want to sleep' });

You can find more details about impure / pure pipes in the docs .

A simple workaround is

<div *ngFor="let o of obj | keyobject:counter">{{o.value}}{{o.key}}</div>

and then increment counter after modification. This avoid creating a new object for each modification.

This works becaues Angular calls the pipe every time the input value changes (object reference for objects) or one of the parameters passed to the pipe.

It can become cumbersome though when the object is modified in a different place in your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM