Why is component/ app "checked" relentlessly without anything happening?

67 views Asked by At
  1. I open Chrome
  2. I started a new stackblitz (ver. 10)
  3. added to app.component ngDoCheck() { console.log('why is this checked without anything happen') }
  4. I do nothing, I even navigate away from the tab.
  5. Why is changeDetection running over and over? This seems like a serious waste of computing.

https://stackblitz.com/edit/angular-ivy-4f8crv?file=src%2Fapp%2Fapp.component.ts

Edit:

  1. plot twist happens on chrome. Not on firefox.

Edit2:

I can confirm that its a "bug" that is prominent on my linix 83... chrome build. The newest does not show such a problem. Therefore im closing this one.

1

There are 1 answers

3
Robert Dempsey On BEST ANSWER

Edit: The solution turned out to be updating to the latest version of Chrome.

In your StackBlitz example, I do not see it getting checked "relentlessly". The app loads and it runs twice, and not again after that.

In a real app it would no doubt get checked a lot more often, and I've forked your StackBlitz here to demonstrate why it happens. Notice how interacting with the text input triggers it quite often?

This article explains Angular Change Detection pretty well, and there are numerous others around the internet, but I'll post a snippet of it here.

The following frequently used browser mechanisms are patched to support change detection: all browser events (click, mouseover, keyup, etc.) setTimeout() and setInterval() Ajax requests In fact, many other browser APIs are patched by Zone.js to transparently trigger Angular change detection, such as for example Websockets. Have a look at the Zone.js test specifications to see what is currently supported.

Essentially, for your Angular app to ensure that it's displaying the data it should be displaying, it needs to run this check after any of the events it determines could possibly update the state of the application fire.

There are numerous methods for reducing the amount of times this check is performed, but the one that will usually give you the most bang for your buck is the OnPush change detection strategy that you can configure your components to use. Using this strategy tells your component to only trigger change detection if a reference of an input in our component changes, an event is triggered in our component or one of its children, or if we run change detection explicitly.