{ "id": "guide/zone", "title": "NgZone", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

NgZonelink

\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.

\n

Fundamentals of change detectionlink

\n

To understand the benefits of NgZone, it is important to have a clear grasp of what change detection is and how it works.

\n

Displaying and updating data in Angularlink

\n

In Angular, you can display data by binding controls in an HTML template to the properties of an Angular component.

\n\nimport { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n template: `\n <h1>{{title}}</h1>\n <h2>My favorite hero is: {{myHero}}</h2>\n `\n})\nexport class AppComponent {\n title = 'Tour of Heroes';\n myHero = 'Windstorm';\n}\n\n\n\n

In 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.

\n\n@Component({\n selector: 'app-click-me',\n template: `\n <button (click)=\"onClickMe()\">Click me!</button>\n {{clickMessage}}`\n})\nexport class ClickMeComponent {\n clickMessage = '';\n\n onClickMe() {\n this.clickMessage = 'You are my hero!';\n }\n}\n\n\n

In 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.

\n

Detecting changes with plain JavaScriptlink

\n

To clarify how changes are detected and values updated, consider the following code written in plain JavaScript.

\n\n<html>\n <div id=\"dataDiv\"></div>\n <button id=\"btn\">updateData</button>\n <canvas id=\"canvas\"></canvas>\n <script>\n let value = 'initialValue';\n // initial rendering\n detectChange();\n\n function renderHTML() {\n document.getElementById('dataDiv').innerText = value;\n }\n\n function detectChange() {\n const currentValue = document.getElementById('dataDiv').innerText;\n if (currentValue !== value) {\n renderHTML();\n }\n }\n\n // Example 1: update data inside button click event handler\n document.getElementById('btn').addEventListener('click', () => {\n // update value\n value = 'button update value';\n // call detectChange manually\n detectChange();\n });\n\n // Example 2: HTTP Request\n const xhr = new XMLHttpRequest();\n xhr.addEventListener('load', function() {\n // get response from server\n value = this.responseText;\n // call detectChange manually\n detectChange();\n });\n xhr.open('GET', serverUrl);\n xhr.send();\n\n // Example 3: setTimeout\n setTimeout(() => {\n // update value inside setTimeout callback\n value = 'timeout update value';\n // call detectChange manually\n detectChange();\n }, 100);\n\n // Example 4: Promise.then\n Promise.resolve('promise resolved a value').then(v => {\n // update value inside Promise thenCallback\n value = v;\n // call detectChange manually\n detectChange();\n }, 100);\n\n // Example 5: some other asynchronous APIs\n document.getElementById('canvas').toBlob(blob => {\n // update value when blob data is created from the canvas\n value = `value updated by canvas, size is ${blob.size}`;\n // call detectChange manually\n detectChange();\n });\n </script>\n</html>\n\n

After 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.

\n

In Angular, this step is unnecessary. Whenever you update the data, your HTML is updated automatically.

\n

When apps update HTMLlink

\n

To understand how change detection works, first consider when the application needs to update the HTML. Typically, updates occur for one of the following reasons:

\n
    \n
  1. \n

    Component 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.

    \n
  2. \n
  3. \n

    Event listener. The DOM event listener can update the data in an Angular component and also trigger change detection, as in the following example.

    \n
  4. \n
\n\n@Component({\n selector: 'app-click-me',\n template: `\n <button (click)=\"onClickMe()\">Click me!</button>\n {{clickMessage}}`\n})\nexport class ClickMeComponent {\n clickMessage = '';\n\n onClickMe() {\n this.clickMessage = 'You are my hero!';\n }\n}\n\n\n
    \n
  1. HTTP Data Request. You can also get data from a server through an HTTP request. For example:
  2. \n
\n\n@Component({\n selector: 'app-root',\n template: '<div>{{data}}</div>';\n})\nexport class AppComponent implements OnInit {\n data = 'initial value';\n serverUrl = 'SERVER_URL';\n constructor(private httpClient: HttpClient) {}\n\n ngOnInit() {\n this.httpClient.get(this.serverUrl).subscribe(response => {\n // user does not need to trigger change detection manually\n this.data = response.data;\n });\n }\n}\n\n
    \n
  1. MacroTasks, such as setTimeout() or setInterval(). You can also update the data in the callback function of a macroTask such as setTimeout(). For example:
  2. \n
\n\n@Component({\n selector: 'app-root',\n template: '<div>{{data}}</div>';\n})\nexport class AppComponent implements OnInit {\n data = 'initial value';\n\n ngOnInit() {\n setTimeout(() => {\n // user does not need to trigger change detection manually\n this.data = 'value updated';\n });\n }\n}\n\n
    \n
  1. MicroTasks, such as Promise.then(). Other asynchronous APIs return a Promise object (such as fetch), so the then() callback function can also update the data. For example:
  2. \n
\n\n@Component({\n selector: 'app-root',\n template: '<div>{{data}}</div>';\n})\nexport class AppComponent implements OnInit {\n data = 'initial value';\n\n ngOnInit() {\n Promise.resolve(1).then(v => {\n // user does not need to trigger change detection manually\n this.data = v;\n });\n }\n}\n\n
    \n
  1. Other async operations. In addition to addEventListener(), setTimeout() and Promise.then(), there are other operations that can update the data asynchronously. Some examples include WebSocket.onmessage() and Canvas.toBlob().
  2. \n
\n

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.

\n

Zones and execution contextslink

\n

A 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:

\n\nconst callback = function() {\n console.log('setTimeout callback context is', this);\n}\n\nconst ctx1 = { name: 'ctx1' };\nconst ctx2 = { name: 'ctx2' };\n\nconst func = function() {\n console.log('caller context is', this);\n setTimeout(callback);\n}\n\nfunc.apply(ctx1);\nfunc.apply(ctx2);\n\n

The 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.

\n

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.

\n\nzone.run(() => {\n // now you are in a zone\n expect(zoneThis).toBe(zone);\n setTimeout(function() {\n // the zoneThis context will be the same zone\n // when the setTimeout is scheduled\n expect(zoneThis).toBe(zone);\n });\n});\n\n

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.

\n

Zones and async lifecycle hookslink

\n

Zone.js can create contexts that persist across asynchronous operations as well as provide lifecycle hooks for asynchronous operations.

\n\nconst zone = Zone.current.fork({\n name: 'zone',\n onScheduleTask: function(delegate, curr, target, task) {\n console.log('new task is scheduled:', task.type, task.source);\n return delegate.scheduleTask(target, task);\n },\n onInvokeTask: function(delegate, curr, target, task, applyThis, applyArgs) {\n console.log('task will be invoked:', task.type, task.source);\n return delegate.invokeTask(target, task, applyThis, applyArgs);\n },\n onHasTask: function(delegate, curr, target, hasTaskState) {\n console.log('task state changed in the zone:', hasTaskState);\n return delegate.hasTask(target, hasTaskState);\n },\n onInvoke: function(delegate, curr, target, callback, applyThis, applyArgs) {\n console.log('the callback will be invoked:', callback);\n return delegate.invoke(target, callback, applyThis, applyArgs);\n }\n});\nzone.run(() => {\n setTimeout(() => {\n console.log('timeout callback is invoked.');\n });\n});\n\n

The above example creates a zone with several hooks.

\n

The 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:

\n\n

These hooks trigger under the following circumstances:

\n\n

With these hooks, Zone can monitor the status of all synchronous and asynchronous operations inside a zone.

\n

The above example returns the following output:

\n\nthe callback will be invoked: () => {\n setTimeout(() => {\n console.log('timeout callback is invoked.');\n });\n}\nnew task is scheduled: macroTask setTimeout\ntask state changed in the zone: { microTask: false,\n macroTask: true,\n eventTask: false,\n change: 'macroTask' }\ntask will be invoked macroTask: setTimeout\ntimeout callback is invoked.\ntask state changed in the zone: { microTask: false,\n macroTask: false,\n eventTask: false,\n change: 'macroTask' }\n\n

All 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.

\n

NgZonelink

\n

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:

\n
    \n
  1. When a sync or async function is executed.
  2. \n
  3. When there is no microTask scheduled.
  4. \n
\n

NgZone run() and runOutsideOfAngular()link

\n

Zone 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.

\n

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.

\n\nexport class AppComponent implements OnInit {\n constructor(private ngZone: NgZone) {}\n ngOnInit() {\n // New async API is not handled by Zone, so you need to\n // use ngZone.run() to make the asynchronous operation in the Angular zone\n // and trigger change detection automatically.\n this.ngZone.run(() => {\n someNewAsyncAPI(() => {\n // update the data of the component\n });\n });\n }\n}\n\n

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().

\n\nexport class AppComponent implements OnInit {\n constructor(private ngZone: NgZone) {}\n ngOnInit() {\n // You know no data will be updated,\n // so you don't want to trigger change detection in this\n // specified operation. Instead, call ngZone.runOutsideAngular()\n this.ngZone.runOutsideAngular(() => {\n setTimeout(() => {\n // update component data\n // but don't trigger change detection.\n });\n });\n }\n}\n\n

Setting up Zone.jslink

\n

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:

\n\n/***************************************************************************************************\n * Zone JS is required by default for Angular itself.\n */\nimport 'zone.js'; // Included with Angular CLI.\n\n

Before importing the zone.js package, you can set the following configurations:

\n\n

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.

\n\n// disable patching requestAnimationFrame\n(window as any).__Zone_disable_requestAnimationFrame = true;\n\n// disable patching specified eventNames\n(window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove'];\n\n

Next, import zone-flags before you import zone.js in the polyfills.ts:

\n\n/***************************************************************************************************\n * Zone JS is required by default for Angular.\n */\nimport `./zone-flags`;\nimport 'zone.js'; // Included with Angular CLI.\n\n

For more information about what you can configure, see the Zone.js documentation.

\n

NoopZonelink

\n

Zone 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.

\n
\n

Disabling Zonelink

\n

If you disable Zone, you will need to trigger all change detection at the correct timing yourself, which requires comprehensive knowledge of change detection.

\n
\n

To remove Zone.js, make the following changes.

\n
    \n
  1. \n

    Remove the zone.js import from polyfills.ts:

    \n\n/***************************************************************************************************\n * Zone JS is required by default for Angular itself.\n */\n// import 'zone.js'; // Included with Angular CLI.\n\n
  2. \n
  3. \n

    Bootstrap Angular with the noop zone in src/main.ts:

    \n\nplatformBrowserDynamic().bootstrapModule(AppModule, { ngZone: 'noop' })\n .catch(err => console.error(err));\n\n
  4. \n
\n\n \n
\n\n\n" }