0

Is there a way to log every time Angular runs change detection on the component?

for example I have three components: foo, bar and baz.

when change detection runs it will console.log:

Run change detection on `foo`.
Run change detection on `bar`.
Run change detection on `baz`.

So this way I'll know which component is running change detection.

Jon Sud
  • 10,211
  • 17
  • 76
  • 174

2 Answers2

0

Yes, implement DoCheck and console.log inside it.

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements DoCheck {
  ngDoCheck() {
    console.log("Change detection reached MyComponent")
  }
}

Explanation: the ngDoCheck method is actually your extension of the component dirty check. Its code will be compiled and added to the factory of your component in the change detection part.

Notice: If you don't see the console.log then the change detection haven't reach your component. This might happen for example of you use onPush strategy and the inputs of the parent component haven't change.

Raz Ronen
  • 2,418
  • 2
  • 14
  • 26
-2

OnCheck

The ngDoCheck method serves the purpose of enhancing the component's dirty checking mechanism, allowing you to detect when change detection is triggered for the component.

However, it is crucial to note that this approach has certain limitations when it comes to components defined with the OnPush strategy. In such cases, the ngDoCheck method is also invoked in the top-level component to ensure that no custom checks are defined by the user.

Nonetheless, for the child components, this can serve as an indication of whether change detection was activated for them. (see Angular ngDoCheck() gets called even with ChangeDetectionStrategy.OnPush)

Binding

add a binding to a function, similar to the following:

    <span>{{ checkChangeDetection() }}</span>

then in ts file

checkChangeDetection() {
    console.log("checked!)
}