在AngularJS或Angular 2中进行手动更改检测? [英] Manual Change Detection in AngularJS or Angular 2?

查看:76
本文介绍了在AngularJS或Angular 2中进行手动更改检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的数据列表,每个元素都应用了一个过滤器.出于性能方面的考虑(我想为每个条目添加很多属性),我只想在数据更改时更新列表(如果更新不佳,可以).不幸的是,每当我单击某些内容时,Angular 2中的OnPush ChangeStrategy仍然会更新.

I have a fairly big list of data and every element has a filter applied. For performance reasons (I want to add a lot of attributes to each entry) I only want to update the list when data changes (it's fine if updating it is unperformant). Unfortunately, the OnPush ChangeStrategy in Angular 2 still updates whenever I click on something.

是否有一种方法只能手动触发更新/检查(例如使用changeDetectorRef.markForCheck()),而不是在每次单击事件时自动将其更新?

Is there a way to ONLY manually trigger updates/checks (using for example changeDetectorRef.markForCheck())and not have it automatic on every click event?

AngularJS(1.5)和Angular 2都可以.

Both AngularJS (1.5) and Angular 2 are fine.

推荐答案

这应该有效(至少它在此

This should work (at least it does in this Plunker):

@Component({
  selector: 'manual',
  template: `<br>manual: {{_counter.obj.counter}}
  <br><button (click)="0">click me</button>
    <li *ngFor="#item of items">{{item}}</li>`,
})
export class Manual {
  items = 'one two'.split(' ');
  constructor(private ref: ChangeDetectorRef, private _counter:Counter) {}
  ngOnInit() {
     this.ref.detach();
     setInterval(_ => {
        this.items.push(`CD ran when counter=${this._counter.obj.counter}`);
        this.ref.reattach();
        this.ref.detectChanges();
        this.ref.detach();
     }, 3000);
  }
}

在插件中,我有一个Counter服务,该服务每秒更新一次obj.counter.在手动"组件中,仅当detectChanges()被称为–时,{{_counter.obj.counter}}(因此才显示视图)才会更新.每3秒.单击click me按钮不会导致视图根据需要进行更新.

In the plunker I have a Counter service that updates obj.counter every second. In the Manual component, {{_counter.obj.counter}} (hence the view) only updates when detectChanges() is called – every 3 seconds. Clicking the click me button does not cause the view to update, as desired.

我没有指定OnPush.但是,如果您这样做,似乎并不会改变所需的操作.

I did not specify OnPush. However, if you do, it does not seem to alter the desired operation.

在插件中,我还有一个自动组件,它的{{_counter.obj.counter}}(因此它的视图)按预期每秒更新一次.

In the plunker I also have an Automatic component, and its {{_counter.obj.counter}} (hence its view) updates every second, as expected.

这篇关于在AngularJS或Angular 2中进行手动更改检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆