Angular ng.core.ChangeDetectionStrategy.onPush如何工作?

Angular ng.core.ChangeDetectionStrategy.onPush如何工作?,angular,angular2-changedetection,Angular,Angular2 Changedetection,若更改检测策略设置为onPush,那个么若组件属性更改,那个么只有组件应该重新渲染 下面是一个示例代码: var SampleComponent1 = ng.core.Component({ selector: "sampleone", template: "{{value}}", viewProviders: [ng.core.ChangeDetectorRef], changeDe

若更改检测策略设置为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(){

            }
        })
var SampleComponent1=ng.core.Component({
选择器:“sampleone”,
模板:“{value}}”,
viewProviders:[ng.core.ChangeDetectorRef],
changeDetection:ng.core.ChangeDetectionStrategy.onPush
}).类({
构造函数:[ng.core.ChangeDetectorRef,函数(cd){
this.cd=cd;
}],
ngOnInit:function(){
这个值=1;
setInterval(函数(){
这个.value++;
}(本),2000年)
}
})
var App=ng.core.Component({
选择器:“应用程序”,
指令:[SampleComponent1],
模板:“”
}).类({
构造函数:函数(){
}
})

在这里,即使属性没有更改,也会渲染模板吗?这是一个bug还是我误解了onPush?

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

changeDetection: ng.core.ChangeDetectionStrategy.onPush
OnPush改为OnPush


查看@yurzui的修复答案,但我想对此发表评论

若更改检测策略设置为onPush,那个么若组件属性更改,那个么只有组件应该重新渲染

不止这些。根据(好吧,它埋在@vivainio的评论中), 使用
OnPush
,Angular仅在以下情况下检查组件的更改(即检查模板绑定)

  • 其任何输入属性(非“组件属性”)发生更改
  • 它触发一个事件(例如,按钮点击)
  • 一个可观察对象触发一个事件,
    async
    管道在视图中与该可观察对象一起使用
有关
OnPush
工作原理的更多信息,请参阅