{ "id": "guide/zone", "title": "NgZone", "contents": "\n\n\n
A zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs.\nThis guide describes how to use Angular's NgZone to automatically detect changes in the component to update HTML.
\nTo understand the benefits of NgZone
, it is important to have a clear grasp of what change detection is and how it works.
In Angular, you can display data by binding controls in an HTML template to the properties of an Angular component.
\nIn addition, you can bind DOM events to a method of an Angular component. In such methods, you can also update a property of the Angular component, which updates the corresponding data displayed in the template.
\nIn both of the above examples, the component's code updates only the property of the component.\nHowever, the HTML is also updated automatically.\nThis guide describes how and when Angular renders the HTML based on the data from the Angular component.
\nTo clarify how changes are detected and values updated, consider the following code written in plain JavaScript.
\nAfter you update the data, you need to call detectChange()
manually to check whether the data changed.\nIf the data changed, you render the HTML to reflect the updated data.
In Angular, this step is unnecessary. Whenever you update the data, your HTML is updated automatically.
\nTo understand how change detection works, first consider when the application needs to update the HTML. Typically, updates occur for one of the following reasons:
\nComponent initialization. For example, when bootstrapping an Angular application, Angular loads the bootstrap component and triggers the ApplicationRef.tick() to call change detection and View Rendering.
\nEvent listener. The DOM event listener can update the data in an Angular component and also trigger change detection, as in the following example.
\nsetTimeout()
or setInterval()
. You can also update the data in the callback function of a macroTask
such as setTimeout()
. For example:Promise.then()
. Other asynchronous APIs return a Promise object (such as fetch
), so the then()
callback function can also update the data. For example:addEventListener()
, setTimeout()
and Promise.then()
, there are other operations that can update the data asynchronously. Some examples include WebSocket.onmessage()
and Canvas.toBlob()
.The preceding list contains most common scenarios in which the application might change the data. Angular runs change detection whenever it detects that data could have changed.\nThe result of change detection is that the DOM is updated with new data. Angular detects the changes in different ways. For component initialization, Angular calls change detection explicitly. For asynchronous operations, Angular uses a zone to detect changes in places where the data could have possibly mutated and it runs change detection automatically.
\nA zone provides an execution context that persists across async tasks. Execution Context is an abstract concept that holds information about the environment within the current code being executed. Consider the following example:
\nThe value of this
in the callback of setTimeout()
might differ depending on when setTimeout()
is called.\nThus, you can lose the context in asynchronous operations.
A zone provides a new zone context other than this
, the zone context that persists across asynchronous operations.\nIn the following example, the new zone context is called zoneThis
.
This new context, zoneThis
, can be retrieved from the setTimeout()
callback function, and this context is the same when the setTimeout()
is scheduled.\nTo get the context, you can call Zone.current
.
Zone.js can create contexts that persist across asynchronous operations as well as provide lifecycle hooks for asynchronous operations.
\nThe above example creates a zone with several hooks.
\nThe onXXXTask
hooks trigger when the status of the task changes.\nThe concept of a Zone Task is very similar to the JavaScript VM Task concept:
macroTask
: such as setTimeout()
microTask
: such as Promise.then()
eventTask
: such as element.addEventListener()
These hooks trigger under the following circumstances:
\nonScheduleTask
: triggers when a new asynchronous task is scheduled, such as when you call setTimeout()
.onInvokeTask
: triggers when an asynchronous task is about to execute, such as when the callback of setTimeout()
is about to execute.onHasTask
: triggers when the status of one kind of task inside a zone changes from stable to unstable or from unstable to stable. A status of \"stable\" means there are no tasks inside the zone, while \"unstable\" means a new task is scheduled in the zone.onInvoke
: triggers when a synchronous function is going to execute in the zone.With these hooks, Zone
can monitor the status of all synchronous and asynchronous operations inside a zone.
The above example returns the following output:
\nAll of the functions of Zone
are provided by a library called Zone.js.\nThis library implements those features by intercepting asynchronous APIs through monkey patching.\nMonkey patching is a technique to add or modify the default behavior of a function at runtime without changing the source code.
While Zone.js can monitor all the states of synchronous and asynchronous operations, Angular additionally provides a service called NgZone.\nThis service creates a zone named angular
to automatically trigger change detection when the following conditions are satisfied:
microTask
scheduled.run()
and runOutsideOfAngular()
linkZone
handles most asynchronous APIs such as setTimeout()
, Promise.then()
, and addEventListener()
.\nFor the full list, see the Zone Module document.\nTherefore in those asynchronous APIs, you don't need to trigger change detection manually.
There are still some third party APIs that Zone does not handle.\nIn those cases, the NgZone
service provides a run()
method that allows you to execute a function inside the Angular zone.\nThis function, and all asynchronous operations in that function, trigger change detection automatically at the correct time.
By default, all asynchronous operations are inside the Angular zone, which triggers change detection automatically.\nAnother common case is when you don't want to trigger change detection.\nIn that situation, you can use another NgZone
method: runOutsideAngular()
.
To make Zone.js available in Angular, you need to import the zone.js
package.\nIf you are using the Angular CLI, this step is done automatically, and you will see the following line in the src/polyfills.ts
:
Before importing the zone.js
package, you can set the following configurations:
requestAnimationFrame()
monkey patch, so the callback of requestAnimationFrame()
will not trigger change detection.\nThis is useful if, in your application, the callback of the requestAnimationFrame()
will not update any data.mousemove
or scroll
event to trigger change detection.There are several other settings you can change.\nTo make these changes, you need to create a zone-flags.ts
file, such as the following.
Next, import zone-flags
before you import zone.js
in the polyfills.ts
:
For more information about what you can configure, see the Zone.js documentation.
\nZone
helps Angular know when to trigger change detection and let the developers focus on the application development.\nBy default, Zone
is loaded and works without additional configuration. However, you don't necessarily have to use Zone
to make Angular work. Instead, you can opt to trigger change detection on your own.
Zone
linkIf you disable Zone
, you will need to trigger all change detection at the correct timing yourself, which requires comprehensive knowledge of change detection.
To remove Zone.js, make the following changes.
\nRemove the zone.js
import from polyfills.ts
:
Bootstrap Angular with the noop
zone in src/main.ts
: