【问题标题】:Angular 2 - *ngFor with keys pipe is not refreshed when object is changedAngular 2 - 更改对象时不会刷新带有键管道的 *ngFor
【发布时间】:2016-12-20 20:23:37
【问题描述】:

我在 *ngfor 循环中使用密钥管道。数据以 JSON 格式提供。

    @Pipe({
      name: 'keys'
    })
    export class KeysPipe implements PipeTransform {
      transform(value, args: string[]): any {
        if (!value) {
          return value;
        }

        let keys = [];
        for (let key in value) {
          keys.push({key: key, value: value[key]});
        }
        return keys;
      }
   }

--

<div *ngFor="let item of jsonObject | keys">
        <p>{{ item.value.code }}</p>
</div>

问题是当我删除 JSON 中的元素时,ngFor 没有更新。

我已经尝试了两个选项:

  • 元素删除后调用this.applicationRef.tick();,没有变化
  • 不纯管道“纯:假”。这导致 chrome 使用了数百 MB 的大量内存,我不得不终止该进程。

还有其他方法吗?

谢谢!

【问题讨论】:

  • 尝试将ChangeDetectionStrategy 设置为OnPush

标签: angular


【解决方案1】:

您可以尝试的一种方法:

delete(id) {
  this.jsonObject = this.jsonObject.filter(x => x.id !== id);
}

这样您就不会改变原始数组。这对管道至关重要

另见

【讨论】:

  • 感谢您为我指明正确的方向。我已经按键名过滤了对象并使用了过滤器和减少。如果有人感兴趣,实际代码在这里:codepen.io/anon/pen/MbxOeG
【解决方案2】:

管道不会运行,除非引用或值发生更改。要解决此问题,请将 pure: false 添加到您的管道装饰器中。见Pipes

例如

@Pipe({
    name: 'keyVal',
    pure: false
})
export class KeyValPipe implements PipeTransform {
    ...
}

编辑我没有看到 OP 已经这样做了。另一种选择是设置一个临时变量,然后将 jsonObject 分配给它,从而创建一个新的引用。你也可以尝试从 temp 到 jsonObject 的深拷贝

【讨论】:

  • OP 说This caused enormous memory usage in chrome in hundreds of MBs and I had to kill the process.
  • 糟糕,那是我的错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 2016-05-25
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
相关资源
最近更新 更多