Search code examples
angularangular2-changedetection

How does ng.core.ChangeDetectionStrategy.onPush work?


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

Here is an example code:

        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(){

            }
        })

Here even if attribute doesn't change the template is rendered? Is this a bug or I misunderstood onPush?


Solution

  • It isn't a bug. You made a mistake:

    changeDetection: ng.core.ChangeDetectionStrategy.onPush
    

    OnPush instead onPush

    Plunker Example