2

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?

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
Narayan Prusty
  • 2,501
  • 3
  • 22
  • 41

3 Answers3

2

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

changeDetection: ng.core.ChangeDetectionStrategy.onPush

OnPush instead onPush

Plunker Example

yurzui
  • 205,937
  • 32
  • 433
  • 399
2

See @yurzui's answer for the fix, but I wanted to comment on

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

It's a bit more than that. According to Savkin's blog post (well, it is buried in a comment to @vivainio), with OnPush, Angular will only check the component for changes (i.e., check the template bindings) when

  • any of its input properties (not "component attributes") changes
  • it fires an event (e.g., a button click)
  • an observable fires an event, and the async pipe is used in the view with that observable

For more info about how OnPush works, please see https://stackoverflow.com/a/36845604/215945

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
0

Angular 4+ Answer

The structure of Angular components has changed since this question was asked.

import { ChangeDetectionStrategy } from '@angular/core';

@Component({
    selector: 'dummy-component',
    templateUrl: './dummy-component.component.html',
    styleUrls: [],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DummyComponent implements OnChanges {
  @Input() sampleInput: string;
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.sampleInput) {
      // Run any trigger when the sampleInput has changed
    }

  }
}
austinthedeveloper
  • 2,401
  • 19
  • 27