0

I have a Plunkr demoing the problem here: https://plnkr.co/edit/e5OVhuWtyStxI1vvXd9h

Summary is:

I have a Parent and Child component. Child has change detection strategy set to onPush.

Child's template is just this:

@Component({
  selector: 'child',
  template: `
  <button (click)="changeHello()">Change</button>
  {{hello}} 
`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {

  hello = "hi";

  ngOnChanges() {
    console.log("on changes called");
  }

  ngDoCheck() {
    console.log("do check called");
  }

  changeHello() {
    this.hello = "goodbye";
  }
}

Why when I click the button everything works and the change actually reflected in the view? (i.e. change from hi to goodbye)

I thought the order of events would be:

  1. User clicks button
  2. The "hello" class property now points to the "goodbye" string
  3. onTurnDone() zone event is invoked and Angular starts performing change detection from the root
  4. When on the root, it notices that none of the Child inputs have changed, and because its Change Detection strategy is set to onPush, it stops there and does not run change detection in the child
  5. The {{hello}} in the template is not updated to goodbye and still displays the old hi

Where have I gone wrong with my above reasoning? Why does ngDoCheck() get called?

Rares Matei
  • 286
  • 1
  • 12
  • See `2. a bound event is triggered from the component (that is your case)` in http://stackoverflow.com/questions/42312075/change-detection-issue-why-is-this-changing-when-its-the-same-object-referen#answer-42312239 – yurzui Feb 26 '17 at 20:08
  • Thank you for this, did not know Angular marks for check when events are triggered from the component! Just so I can avoid possible duplication in the future, how did you find this link? Did you remember it from reading it before? If you found it by searching, what did you search for to get that results? – Rares Matei Feb 26 '17 at 22:22

0 Answers0