简体   繁体   English

Angular2 / 4如何在* ngFor中更新模板在[object,object]上工作?

[英]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 我想在模板中迭代此对象,所以我使用管道帮助,因为没有直接方法可以在Angular2 / 4中的模板中迭代obj

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. 在我的Javascript中,如果要对Json对象进行任何更改,则动态更改不会反映在模板上。

obj.TimSays = "i want to sleep"; obj.TimSays =“我想睡觉”;

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. 我需要在这里做些什么,以防模板和ngFOr(Object)像双向绑定一样工作。

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 : 最好在修改对象时通过创建新引用来对输入执行“纯”更改,例如,使用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. 然后在修改后递增counter 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. 这是因为每当输入值更改(对象的对象引用)或传递给管道的参数之一更改时,Angular都会调用管道。

It can become cumbersome though when the object is modified in a different place in your application. 但是,如果在应用程序的其他位置修改对象,则可能会变得很麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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