ng.core.ChangeDetectionStrategy.onPush 是如何工作的?

How does ng.core.ChangeDetectionStrategy.onPush work?

如果更改检测策略设置为 onPush,那么如果组件属性发生更改,则仅应重新渲染组件。

这是一个示例代码:

        var SampleComponent1 = ng.core.Component({
            selector: "sampleone",
            template: "{{value}}",
            viewProviders: [ng.core.ChangeDetectorRef],
            changeDetection: ng.core.ChangeDetectionStrategy.onPush
        }).Class({
            constructor: [ng.core.ChangeDetectorRef, function(cd){
                this.cd = cd;
            }],
            ngOnInit: function(){
                this.value = 1;
                setInterval(function(){
                    this.value++;
                }.bind(this), 2000)
            }
        })

        var App = ng.core.Component({
            selector: "app",
            directives: [SampleComponent1],
            template: "<sampleone ></sampleone>"
        }).Class({
            constructor: function(){

            }
        })

这里即使属性不改变模板也被渲染了?这是一个错误还是我误解了onPush?

这不是错误。你犯了一个错误:

changeDetection: ng.core.ChangeDetectionStrategy.onPush

OnPush 而不是 onPush

Plunker Example

查看@yurzui 的修复答案,但我想对

发表评论

If change detection strategy is set to onPush then if component attributes change then only component should be re-rendered.

不止于此。根据 Savkin's blog post(好吧,它隐藏在对@vivainio 的评论中), 使用 OnPush,Angular 将仅在

时检查组件的更改(即检查模板绑定)
  • 其任何输入属性(不是"component attributes")更改
  • 它触发一个事件(例如,单击按钮)
  • 一个 observable 触发一个事件,并且 async 管道在具有该 observable 的视图中使用

有关 OnPush 工作原理的更多信息,请参阅