testing
testing

Reputation: 2343

How do we detect that Change Detection is been ran in Angular2 without direct @Output?

Consider the following component tree structure in Angular2

    A
  B 
D  E  

If D emits an event via click to B , angular2 will automatically start the change detection from root A. Is there a way to console.log that change detection out even if D is not directly emitting event to A ?

For example in D

html

<div (click)="update($event)"></div>

component

@Output() myOutputName = new EventEmitter();

update(event) {
    this.myOutputName.emit('some vlaue'); 
}

In B

(myOutputName)="update($event)"

But if B doesn't further that event I have no way to tell if A is running its change detection.

The motivation for this is to figure out which component has Change Detection running for debugging purpose

Upvotes: 1

Views: 472

Answers (1)

Mark Rajcok
Mark Rajcok

Reputation: 364707

Implement ngDoCheck() on each component. It is a lifecycle hook that is called every time change detection runs on a component.

See also https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#docheck

Note however, that just because the method is called doesn't necessarily mean that the template bindings have been checked for changes. I believe (I could be wrong, this is from memory, when I played with a plunker a while ago) that even if the first OnPush component is not marked, ngDoCheck() is still called, but I don't think the template bindings are checked. Also, if the OnPush component was not marked for check, ngDoCheck() is not called on descendant components.

Upvotes: 2

Related Questions