【问题标题】:Angular 2: view does not update when array is updatedAngular 2:更新数组时视图不更新
【发布时间】:2017-07-05 13:13:16
【问题描述】:

我有一个包含两个数组的组件。 arrayAarrayBarrayB 包含 arrayA 的过滤元素。并在模板中:

<div *ngFor="let elem of arrayB">{{elem.something}}</div>

我也有一个按钮:

<button (click)="doSomething()">Do Something</button>

doSomething 方法中,我使用arrayA 上的过滤器方法来更新arrayB

doSomething() {
    this.arrayB = this.arrayA.filter(elem => { return ***some code***; });
}

问题是视图没有刷新。我尝试使用 NgZone(ngZone.run():我将代码包装在方法中。)和 ChangeDetectorRef(detectChanges()/markForCheck():我在方法结束时调用了它。)。

这个问题应该怎么解决?

【问题讨论】:

  • console.log(this.arrayB) 最后在doSomething func 看看是否真的有什么不同
  • 如果按钮单击事件发生在与 ngFor 相同的模板内,则不必将任何内容标记为已更改。如果它在更改树之外或在检查后更改,您只需告诉 Angular 它已更改。也许问题是 arrayB 并没有在你认为应该改变的时候改变。
  • @Dhyey 在我用console.log(arrayB) 检查数组后,我注意到一个奇怪的事情:doSomething() 触发了两次。第一次,arrayB 是正确的(过滤),但第二次......它是原始的。我的(click) 看起来像这样:(click)="foo &amp;&amp; !foo.bar &amp;&amp; doSomething()"。所以我想问题是这些“条件”。
  • @Dhyey 我错了。没有“条件”,它仍然会触发两次。
  • @RolandRácz 你能在 plnkr 中复制它并发布链接吗?

标签: angular angular2-changedetection


【解决方案1】:

它应该有效!确保您的过滤器正常工作,请检查此示例:

<div *ngFor="let elemB of arrayB">{{elemB}}</div>
<strong>array A :</strong>
<div *ngFor="let elemA of arrayA">{{elemA}}</div>
<button (click)="doSomething()">Do Something</button>

TS:

 arrayA = [0,1,2,3,4];
 arrayB = [];

 doSomething(){ 
     this.arrayB = this.arrayA.filter(x => { return x > 2; });
 }

https://plnkr.co/edit/VQYoVIGoioPwjW1ThcFQ?p=preview

【讨论】:

  • 感谢您的回答。事实证明,过滤器很好,但doSomething() 会触发两次(即使我只点击了一次)。第一次,arrayB 是对的,但第二次是原始的。问题是,为什么会出现这种行为。
【解决方案2】:

doSomething() 方法中,我返回了true。因此,该方法触发了两次。 所以解决方案是始终返回false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2016-09-06
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多