docs: 翻译遗漏的文档

This commit is contained in:
Zhicheng WANG 2021-02-05 14:42:34 +08:00
parent 497a2bfaf1
commit 9b60ef0392
4 changed files with 221 additions and 9 deletions

View File

@ -1,12 +1,21 @@
# `tslib` direct dependency migration
# `tslib` 直接依赖项迁移
## What does this migration do?
## 此迁移有什么用?
If you have any libraries within your workspace, this migration will convert `tslib` peer dependencies to direct dependencies for the libraries.
TypeScript uses the `tslib` package to provide common helper functions used in compiled TypeScript code.
The `tslib` version is also updated to `2.0.0` to support TypeScript 3.9.
如果你的工作空间中有任何库,此迁移会将它们对 `tslib` 的平级依赖转换为直接依赖。TypeScript 使用 `tslib` 包来提供 TypeScript 编译后代码中使用的常用辅助函数。`tslib` 版本也更新为 `2.0.0` 以支持 TypeScript 3.9。
Before:
之前:
```json
{
"name": "my-lib",
@ -20,6 +29,9 @@ Before:
```
After:
之后:
```json
{
"name": "my-lib",
@ -36,17 +48,26 @@ After:
## Why is this migration necessary?
## 为什么需要进行此迁移?
The [`tslib`](https://github.com/Microsoft/tslib) is a runtime library for Typescript.
The version of this library is bound to the version of the TypeScript compiler used to compile a library.
Peer dependencies do not accurately represent this relationship between the runtime and the compiler.
If `tslib` remained declared as a library peer dependency, it would be possible for some Angular workspaces to get into a state where the workspace could not satisfy `tslib` peer dependency requirements for multiple libraries, resulting in build-time or run-time errors.
[`tslib`](https://github.com/Microsoft/tslib) 是 Typescript 的运行时库。该库的版本绑定到了用于编译库的 TypeScript 编译器的版本。平级依赖不能准确表达此运行时库与编译器之间的这种关系。如果 `tslib` 仍然声明为库对等依赖项,则某些 Angular 工作空间可能会出现工作空间无法满足 `tslib` 平级依赖项要求的状态,从而导致构建期或运行期错误。
As of TypeScript 3.9 (used by Angular v10), `tslib` version of 2.x is required to build new applications.
However, older libraries built with previous version of TypeScript and already published to npm might need `tslib` 1.x.
This migration makes it possible for code depending on incompatible versions of the `tslib` runtime library to remain interoperable.
从 TypeScript 3.9(由 Angular v10 使用)开始,需要 `tslib` 版本 2.x 来构建新的应用程序。但是,使用以前的 TypeScript 版本构建并已发布到 npm 的较早的库可能需要 `tslib` 。这种迁移使依赖于 `tslib` 运行时库的某个不兼容版本的代码可以保持互操作性。
## Do I still need `tslib` as a dependency in my workspace `package.json`?
## 我是否仍需要 `tslib` 作为我的工作区 `package.json` 的依赖项?
Yes.
The `tslib` dependency declared in the `package.json` file of the workspace is used to build applications within this workspace, as well as run unit tests for workspace libraries, and is required.
是。`package.json` 文件中声明的 `tslib` 依赖用于在此工作空间内构建应用程序,以及对工作空间中的库进行运行单元测试,这是必要的。

View File

@ -1,33 +1,57 @@
# Update `module` and `target` compiler options migration
# 更新 `module``target` 编译器选项的迁移
## What does this migration do?
## 此迁移有什么作用?
This migration adjusts the [`target`](https://www.typescriptlang.org/v2/en/tsconfig#target) and [`module`](https://www.typescriptlang.org/v2/en/tsconfig#module) settings within the [TypeScript configuration files](guide/typescript-configuration) for the workspace.
The changes to each option vary based on the builder or command that uses the TypeScript configuration file.
Unless otherwise noted, changes are only made if the existing value was not changed since the project was created.
This process helps ensure that intentional changes to the options are kept in place.
TypeScript Configuration File(s) | Changed Property | Existing Value | New Value
------------- | ------------- | ------------- | ------------- | -------------
`<workspace base>/tsconfig.json` | `"module"` | `"esnext"` | `"es2020"`
Used in `browser` builder options (`ng build` for applications) | `"module"` | `"esnext"` | `"es2020"`
Used in `ng-packgr` builder options (`ng build` for libraries) | `"module"` | `"esnext"` | `"es2020"`
Used in `karma` builder options (`ng test` for applications) | `"module"` | `"esnext"` | `"es2020"`
Used in `server` builder options (universal) | `"module"` | `"commonjs"` | _removed_
Used in `server` builder options (universal) | `"target"` | _any_ | `"es2016"`
Used in `protractor` builder options (`ng e2e` for applications) | `"target"` | `"es5"` | `"es2018"`
此迁移将调整工作区的 [TypeScript 配置文件](guide/typescript-configuration)中的 [`target`](https://www.typescriptlang.org/v2/en/tsconfig#target) 和 [`module`](https://www.typescriptlang.org/v2/en/tsconfig#module) 设置。对每个选项的更改根据使用 TypeScript 配置文件的构建器或命令而有所不同。除非另有说明,否则仅当自创建项目以来未更改过现有值的情况下才进行更改。此过程有助于确保对这些选项进行的更改都是符合意图的。
| TypeScript Configuration File(s) | Changed Property | Existing Value | New Value |
| -------------------------------- | ---------------- | -------------- | --------- |
| TypeScript 配置文件 | 属性变更 | 现有值 | 新值 |
| `<workspace base>/tsconfig.json` | `"module"` | `"esnext"` | `"es2020"` |
| Used in `browser` builder options (`ng build` for applications) | `"module"` | `"esnext"` | `"es2020"` |
| 在 `browser` 构建器选项中使用(用于应用程序的 `ng build`| `"module"` | `"esnext"` | `"es2020"` |
| Used in `ng-packgr` builder options (`ng build` for libraries) | `"module"` | `"esnext"` | `"es2020"` |
| 在 `ng-packgr` 构建器选项中使用(用于库的 `ng build`| `"module"` | `"esnext"` | `"es2020"` |
| Used in `karma` builder options (`ng test` for applications) | `"module"` | `"esnext"` | `"es2020"` |
| 在 `karma` 器选项中使用(用于应用程序的 `ng test`| `"module"` | `"esnext"` | `"es2020"` |
| Used in `server` builder options (universal) | `"module"` | `"commonjs"` | *removed* |
| 在 `server` 构建器选项中使用(通用) | `"module"` | `"commonjs"` | *已移除* |
| Used in `server` builder options (universal) | `"target"` | *any* | `"es2016"` |
| 在 `server` 构建器选项中使用(通用) | `"target"` | *任何* | `"es2016"` |
| Used in `protractor` builder options (`ng e2e` for applications) | `"target"` | `"es5"` | `"es2018"` |
| 在 `protractor` 构建器选项中使用(用于应用程序的 `ng e2e`| `"target"` | `"es5"` | `"es2018"` |
## Why is this migration necessary?
## 为什么需要此迁移?
This migration provides improvements to the long-term supportability of projects by updating the projects to use recommended best practice compilation options.
此迁移通过更新项目,让它使用建议的最佳实践编译选项,来改善项目的长期支持能力。
For the functionality that executes on Node.js, such as Universal and Protractor, the new settings provide performance and troubleshooting benefits as well.
The minimum Node.js version for the Angular CLI (v10.13) supports features in ES2018 and earlier.
By targeting later ES versions, the compiler transforms less code and can use newer features directly.
Since zone.js does not support native `async` and `await`, the universal builds still target ES2016.
对于要在 Node.js 上执行的功能(例如 Universal 和 Protractor新设置还提供了性能和故障排除方面的优势。Angular CLI 的最低 Node.js 版本v10.13)支持 ES2018 及更早版本中的功能。通过瞄准更高版本的 ES编译器可以转换更少的代码并且可以直接使用新特性。由于 zone.js 不支持原生 `async``await` ,因此通用版本仍以 ES2016 为目标。
## Why `"es2020"` instead of `"esnext"`?
## 为什么用 `"es2020"` 代替 `"esnext"`
In TypeScript 3.9, the behavior of the TypeScript compiler controlled by `module` is the same with both `"esnext"` and `"es2020"` values.
This behavior can change in the future, because the `"esnext"` option could evolve in a backwards incompatible ways, resulting in build-time or run-time errors during a TypeScript update.
As a result, code can become unstable. Using the `"es2020"` option mitigates this risk.
在 TypeScript 3.9 中,由 `module` 控制的 TypeScript 编译器的行为与 `"esnext"``"es2020"` 值相同。此行为将来可能会更改,因为 `"esnext"` 选项可能会以向后不兼容的方式发展,从而导致在 TypeScript 更新时导致构建期或运行期错误。其后果是,代码可能变得不稳定。使用 `"es2020"` 选项可减轻此风险。

View File

@ -1,61 +1,98 @@
# Template expression operators
# 模板表达式运算符
<div class="callout is-critical">
<header>Marked for archiving</header>
<header>已标记为归档</header>
To ensure that you have the best experience possible, this topic is marked for archiving until we determine that it clearly conveys the most accurate information possible.
为确保你拥有最佳的体验,本主题已标记为存档,直到我们确定其清楚地传达了最准确的信息为止。
In the meantime, this topic might be helpful: [Hierarchical injectors](guide/hierarchical-dependency-injection).
同时,下列主题可能会有所帮助:[分层注入器](guide/hierarchical-dependency-injection)。
If you think this content should not be archived, please file a [GitHub issue](https://github.com/angular/angular/issues/new?template=3-docs-bug.md).
如果你认为不应将此内容存档,请提交 [GitHub 问题](https://github.com/angular/angular/issues/new?template=3-docs-bug.md)。
</div>
The Angular template expression language employs a subset of JavaScript syntax supplemented with a few special operators
for specific scenarios.
Angular 模板表达语言采用了 JavaScript 语法的子集,并为特定情况添加了一些特殊的运算符。
<div class="alert is-helpful">
See the <live-example></live-example> for a working example containing the code snippets in this guide.
有关包含本指南中代码片段的有效示例,请参见<live-example></live-example>
</div>
{@a non-null-assertion-operator}
## The non-null assertion operator ( `!` )
## 非空断言运算符( `!`
When you use TypeScript's `--strictNullChecks` flag, you can prevent the type checker from throwing an error with Angular's non-null assertion operator, `!`.
使用 TypeScript 的 `--strictNullChecks` 标志时,可以防止类型检查器使用 Angular 的非空断言运算符 `!`
The Angular non-null assertion operator causes the TypeScript type checker to suspend strict `null` and `undefined` checks for a specific property expression.
Angular 非空断言运算符使 TypeScript 类型检查器暂停对特定属性表达式的 `null``undefined` 的严格检查。
For example, you can assert that `item` properties are also defined.
例如,你可以断言 `item` 也是已定义的。
<code-example path="template-expression-operators/src/app/app.component.html" region="non-null" header="src/app/app.component.html"></code-example>
Often, you want to make sure that any property bindings aren't `null` or `undefined`.
However, there are situations in which such states are acceptable.
For those situations, you can use Angular's non-null assertion operator to prevent TypeScript from reporting that a property is `null` or `undefined`.
通常,你要确保任何属性绑定都不为 `null``undefined` 。但是,在某些情况下,这种状态是可以接受的。对于这些情况,可以使用 Angular 的非空断言运算符来防止 TypeScript 报告某个属性为 `null``undefined`
The non-null assertion operator, `!`, is optional unless you turn on strict null checks.
非空断言运算符 `!` 是可选的,除非你要启用严格的空检查。
For more information, see TypeScript's [strict null checking](http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html "Strict null checking in TypeScript").
有关更多信息,请参见 TypeScript 的[严格空检查](http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html "TypeScript 中严格的 null 检查")。
{@a any-type-cast-function}
## The `$any()` type cast function
## `$any()` 类型转换函数
Sometimes a binding expression triggers a type error during [AOT compilation](guide/aot-compiler) and it is not possible or difficult to fully specify the type.
To silence the error, you can use the `$any()` cast function to cast
the expression to the [`any` type](https://www.typescriptlang.org/docs/handbook/basic-types.html#any) as in the following example:
有时,绑定表达式会在 [AOT 编译](guide/aot-compiler)期间触发类型错误,并且不可能或很难完全指定类型。要使此错误静音,可以使用 `$any()` 强制转换函数把表达式强制转换为 [`any` 类型](https://www.typescriptlang.org/docs/handbook/basic-types.html#any),如下例所示:
<code-example path="built-in-template-functions/src/app/app.component.html" region="any-type-cast-function-1" header="src/app/app.component.html"></code-example>
Using `$any()` prevents TypeScript from reporting that `bestByDate` is not a member of the `item` object.
使用 `$any()` 可以防止 TypeScript 报告 `bestByDate` 不是 `item` 对象成员的错误。
The `$any()` cast function also works with `this` to allow access to undeclared members of the component.
`$any()` 强制转换函数也可以与 `this` 一起使用,以允许访问组件的未声明成员。
<code-example path="built-in-template-functions/src/app/app.component.html" region="any-type-cast-function-2" header="src/app/app.component.html"></code-example>
The `$any()` cast function works anywhere in a binding expression where a method call is valid.
`$any()` 强制转换函数可在绑定表达式中任何进行方法调用的地方使用。

View File

@ -3,28 +3,46 @@
A zone is an execution context that persists across async tasks. You can think of it as [thread-local storage](https://en.wikipedia.org/wiki/Thread-local_storage) for JavaScript VMs.
This guide describes how to use Angular's NgZone to automatically detect changes in the component to update HTML.
Zone 是跨异步任务而持久存在的执行上下文。你可以将其视为 JavaScript VM 中的[线程本地存储](https://en.wikipedia.org/wiki/Thread-local_storage)。本指南介绍了如何使用 Angular 的 的 NgZone 自动检测组件中的更改以更新 HTML。
## Fundamentals of change detection
## 变更检测的基础
To understand the benefits of `NgZone`, it is important to have a clear grasp of what change detection is and how it works.
要理解 `NgZone` 的好处,重要的是要清楚地了解什么是变更检测以及它的工作原理。
### Displaying and updating data in Angular
### 在 Angular 中显示和更新数据
In Angular, you can display data by binding controls in an HTML template to the properties of an Angular component.
在 Angular 中,你可以通过把 HTML 模板中的控件绑定到 Angular 组件的属性来显示数据。
<code-example path="displaying-data/src/app/app.component.1.ts" header="src/app/app.component.ts"></code-example>
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.
另外,你也可以将 DOM 事件绑定到 Angular 组件中的方法。在此类方法中,你还可以更新 Angular 组件的属性,该属性将更新模板中显示的相应数据。
<code-example path="user-input/src/app/click-me.component.ts" region="click-me-component" header="src/app/click-me.component.ts"></code-example>
In both of the above examples, the component's code updates only the property of the component.
However, the HTML is also updated automatically.
This guide describes how and when Angular renders the HTML based on the data from the Angular component.
在以上两个示例中组件的代码仅更新组件的属性。但是HTML 也会自动更新。本指南介绍了 Angular 如何以及何时根据 Angular 组件中的数据渲染 HTML。
### Detecting changes with plain JavaScript
### 使用普通Plain JavaScript 检测更改
To clarify how changes are detected and values updated, consider the following code written in plain JavaScript.
为了阐明如何检测到更改和更新值,请考虑以下用普通 JavaScript 编写的代码。
```javascript
<html>
<div id="dataDiv"></div>
@ -95,20 +113,34 @@ To clarify how changes are detected and values updated, consider the following c
After you update the data, you need to call `detectChange()` manually to check whether the data changed.
If the data changed, you render the HTML to reflect the updated data.
更新数据后,需要调用 `detectChange()` 来检查数据是否已更改。如果数据已更改,则渲染 HTML 以反映更新的数据。
In Angular, this step is unnecessary. Whenever you update the data, your HTML is updated automatically.
在 Angular 中,此步骤是不必要的。每当你更新数据时,你的 HTML 都会自动更新。
### When apps update HTML
### 应用何时更新 HTML
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:
要了解变更检测的工作原理,请首先考虑应用程序何时需要更新 HTML。通常会由于以下原因之一而发生更新
1. Component initialization. For example, when bootstrapping an Angular application, Angular loads the bootstrap component and triggers the [ApplicationRef.tick()](api/core/ApplicationRef#tick) to call change detection and View Rendering.
组件初始化。例如,当引导 Angular 应用程序时Angular 会加载引导组件并触发 [ApplicationRef.tick](api/core/ApplicationRef#tick) 来调用变更检测和视图渲染。
1. Event listener. The DOM event listener can update the data in an Angular component and also trigger change detection, as in the following example.
事件监听器。 DOM 事件侦听器可以更新 Angular 组件中的数据,还可以触发变更检测,如下例所示。
<code-example path="user-input/src/app/click-me.component.ts" region="click-me-component" header="src/app/click-me.component.ts"></code-example>
3. HTTP Data Request. You can also get data from a server through an HTTP request. For example:
HTTP 数据请求。你还可以通过 HTTP 请求从服务器获取数据。例如:
```typescript
@Component({
selector: 'app-root',
@ -130,6 +162,8 @@ export class AppComponent implements OnInit {
4. MacroTasks, such as `setTimeout()` or `setInterval()`. You can also update the data in the callback function of a `macroTask` such as `setTimeout()`. For example:
宏任务,例如 `setTimeout()``setInterval()` 。你还可以在诸如 `setTimeout()` `macroTask` 的回调函数中更新数据。例如:
```typescript
@Component({
selector: 'app-root',
@ -149,6 +183,8 @@ export class AppComponent implements OnInit {
5. 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:
微任务,例如 `Promise.then()`。其他异步 API例如 `fetch`)会返回 Promise 对象,因此 `then()` 回调函数也可以更新数据。例如:
```typescript
@Component({
selector: 'app-root',
@ -168,13 +204,21 @@ export class AppComponent implements OnInit {
6. 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()`.
其他异步操作。除了 `addEventListener()` `setTimeout()``Promise.then()` ,还有其他一些操作可以异步更新数据。比如 `WebSocket.onmessage()``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.
The 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](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous), Angular uses a zone to detect changes in places where the data could have possibly mutated and it runs change detection automatically.
前面的列表包含应用程序可能会在其中更改数据的最常见场景。只要 Angular 检测到数据可能已更改,就会运行变更检测。变更检测的结果是 DOM 被这些新数据更新。Angular 会以不同的方式检测变化。对于组件初始化Angular 调用显式变更检测。对于[异步操作](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous)Angular 会使用 Zone 在数据可能被修改的地方检测变化,并自动运行变更检测。
## Zones and execution contexts
## Zone 和执行上下文
A zone provides an execution context that persists across async tasks. [Execution Context](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) is an abstract concept that holds information about the environment within the current code being executed. Consider the following example:
Zone 提供了在异步任务之间持久存在的执行上下文。[执行上下文](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)是一个抽象概念,用于在当前执行的代码中保存有关环境的信息。考虑以下示例:
```javascript
const callback = function() {
console.log('setTimeout callback context is', this);
@ -195,9 +239,13 @@ func.apply(ctx2);
The value of `this` in the callback of `setTimeout()` might differ depending on when `setTimeout()` is called.
Thus, you can lose the context in asynchronous operations.
`setTimeout()` 回调中的 `this` 值可能会有所不同,具体取决于 `setTimeout()` 的调用时机。因此,你可能会在异步操作中丢失上下文。
A zone provides a new zone context other than `this`, the zone context that persists across asynchronous operations.
In the following example, the new zone context is called `zoneThis`.
Zone 提供了不同于 `this` 的新的 Zone 上下文,该 Zone 上下文在异步操作中保持不变。在下例中,新的 Zone 上下文称为 `zoneThis`
```javascript
zone.run(() => {
// now you are in a zone
@ -213,10 +261,16 @@ zone.run(() => {
This new context, `zoneThis`, can be retrieved from the `setTimeout()` callback function, and this context is the same when the `setTimeout()` is scheduled.
To get the context, you can call [`Zone.current`](https://github.com/angular/angular/blob/master/packages/zone.js/lib/zone.ts).
新的上下文 `zoneThis` 可以从 `setTimeout()` 的回调函数中检索出来,这个上下文和调用 `setTimeout()` 时的上下文是一样的。要获取此上下文,可以调用 [`Zone.current`](https://github.com/angular/angular/blob/master/packages/zone.js/lib/zone.ts)。
## Zones and async lifecycle hooks
## Zone 和异步生命周期钩子
Zone.js can create contexts that persist across asynchronous operations as well as provide lifecycle hooks for asynchronous operations.
Zone.js 可以创建在异步操作中持久存在的上下文,并为异步操作提供生命周期钩子。
```javascript
const zone = Zone.current.fork({
name: 'zone',
@ -246,23 +300,53 @@ zone.run(() => {
The above example creates a zone with several hooks.
上面的示例创建了一个具有多个钩子的 Zone。
The `onXXXTask` hooks trigger when the status of the task changes.
The concept of a *Zone Task* is very similar to the JavaScript VM Task concept:
当任务状态更改时,就会触发 `onXXXTask` 钩子。*Zone 任务*的概念与 JavaScript VM 中任务的概念非常相似:
- `macroTask`: such as `setTimeout()`
`macroTask`:例如 `setTimeout()`
- `microTask`: such as `Promise.then()`
`microTask`:例如 `Promise.then()`
- `eventTask`: such as `element.addEventListener()`
`eventTask`:例如 `element.addEventListener()`
These hooks trigger under the following circumstances:
这些钩子在以下情况下触发:
- `onScheduleTask`: triggers when a new asynchronous task is scheduled, such as when you call `setTimeout()`.
`onScheduleTask`:在计划新的异步任务时触发,例如调用 `setTimeout()` 时。
- `onInvokeTask`: triggers when an asynchronous task is about to execute, such as when the callback of `setTimeout()` is about to execute.
`onInvokeTask`:在异步任务即将执行时触发,例如 `setTimeout()` 的回调即将执行时。
- `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.
`onHasTask`:当 Zone 内的一种任务的状态从稳定变为不稳定或从不稳定变为稳定时触发。状态“稳定”表示该 Zone 内没有任务,而“不稳定”表示在该 Zone 中计划了新任务。
- `onInvoke`: triggers when a synchronous function is going to execute in the zone.
`onInvoke`:将在 Zone 中执行同步函数时触发。
With these hooks, `Zone` can monitor the status of all synchronous and asynchronous operations inside a zone.
使用这些钩子,`Zone` 可以监视 Zone 内所有同步和异步操作的状态。
The above example returns the following output:
上面的示例返回以下输出:
```
the callback will be invoked: () => {
setTimeout(() => {
@ -286,24 +370,39 @@ All of the functions of `Zone` are provided by a library called [Zone.js](https:
This library implements those features by intercepting asynchronous APIs through monkey patching.
Monkey patching is a technique to add or modify the default behavior of a function at runtime without changing the source code.
`Zone` 的所有功能均由名为 [Zone.js](https://github.com/angular/angular/tree/master/packages/zone.js/README.md) 的库提供。该库通过猴子补丁拦截异步 API 来实现这些功能。猴子补丁是一种在运行时添加或修改函数默认行为而无需更改源代码的技术。
## NgZone
While Zone.js can monitor all the states of synchronous and asynchronous operations, Angular additionally provides a service called NgZone.
This service creates a zone named `angular` to automatically trigger change detection when the following conditions are satisfied:
虽然 Zone.js 可以监视同步和异步操作的所有状态,但 Angular 还提供了一项名为 NgZone 的服务。满足以下条件时,此服务会创建一个名为 `angular` 的 Zone 来自动触发变更检测。
1. When a sync or async function is executed.
当执行同步或异步功能时。
1. When there is no `microTask` scheduled.
已经没有已计划的 `microTask`
### NgZone `run()` and `runOutsideOfAngular()`
### NgZone `run()``runOutsideOfAngular()`
`Zone` handles most asynchronous APIs such as `setTimeout()`, `Promise.then()`, and `addEventListener()`.
For the full list, see the [Zone Module document](https://github.com/angular/angular/blob/master/packages/zone.js/MODULE.md).
Therefore in those asynchronous APIs, you don't need to trigger change detection manually.
`Zone` 处理大多数异步 API例如 `setTimeout()`、`Promise.then()` 和 `addEventListener()` 。有关完整列表,请参见 [Zone 模块的文档](https://github.com/angular/angular/blob/master/packages/zone.js/MODULE.md)。因此,在这些异步 API 中,你无需手动触发变更检测。
There are still some third party APIs that Zone does not handle.
In those cases, the `NgZone` service provides a [`run()`](api/core/NgZone#run) method that allows you to execute a function inside the angular zone.
This function, and all asynchronous operations in that function, trigger change detection automatically at the correct time.
仍然有一些 Zone 无法处理的第三方 API。在这种情况下`NgZone` 服务提供了 [`run()`](api/core/NgZone#run) 方法,该方法允许你在 `angular` Zone 中执行函数。此函数以及该函数中的所有异步操作会在正确的时间自动触发变更检测。
```typescript
export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
@ -324,6 +423,8 @@ By default, all asynchronous operations are inside the angular zone, which trigg
Another common case is when you don't want to trigger change detection.
In that situation, you can use another `NgZone` method: [`runOutsideAngular()`](api/core/NgZone#runoutsideangular).
默认情况下,所有异步操作都在 angular Zone 内,这会自动触发变更检测。另一个常见的情况是你不想触发变更检测。在这种情况下,你可以使用另一个 `NgZone` 方法:[`runOutsideAngular()`](api/core/NgZone#runoutsideangular) 。
```typescript
export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
@ -343,9 +444,13 @@ export class AppComponent implements OnInit {
### Setting up Zone.js
### 设置 Zone.js
To make Zone.js available in Angular, you need to import the `zone.js` package.
If you are using the Angular CLI, this step is done automatically, and you will see the following line in the `src/polyfills.ts`:
为了使 Zone.js 在 Angular 中可用,你需要导入 `zone.js` 包。如果使用的是 Angular CLI则此步骤将自动完成并且你会在 `src/polyfills.ts` 中看到以下行:
```typescript
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
@ -355,14 +460,23 @@ import 'zone.js/dist/zone'; // Included with Angular CLI.
Before importing the `zone.js` package, you can set the following configurations:
在导入 `zone.js` 软件包之前,你可以做如下配置:
- You can disable some asynchronous API monkey patching for better performance.
For example, you can disable the `requestAnimationFrame()` monkey patch, so the callback of `requestAnimationFrame()` will not trigger change detection.
This is useful if, in your application, the callback of the `requestAnimationFrame()` will not update any data.
你可以禁用一些异步 API 的猴子补丁,以获得更好的性能。例如,你可以禁用 `requestAnimationFrame()` 的猴子补丁,这样 `requestAnimationFrame()` 的回调就不会触发变更检测。如果你的应用程序不会在 `requestAnimationFrame()` 回调中更新任何数据,则这种方式很有用。
- You can specify that certain DOM events do not run inside the angular zone; for example, to prevent a `mousemove` or `scroll` event to trigger change detection.
你可以指定某些 DOM 事件不在 angular Zone 内运行;例如,为了防止 `mousemove``scroll` 事件来触发变更检测。
There are several other settings you can change.
To make these changes, you need to create a `zone-flags.ts` file, such as the following.
你还可以更改另外几个设置。要进行这些更改,你需要创建一个 `zone-flags.ts` 文件,如下所示。
```typescript
// disable patching requestAnimationFrame
(window as any).__Zone_disable_requestAnimationFrame = true;
@ -373,6 +487,8 @@ To make these changes, you need to create a `zone-flags.ts` file, such as the fo
Next, import `zone-flags` before you import `zone.js` in the `polyfills.ts`:
接着,在 `polyfills.ts` 中导入 `zone.js` 之前先导入 `zone-flags`
```typescript
/***************************************************************************************************
* Zone JS is required by default for Angular.
@ -383,23 +499,35 @@ import 'zone.js/dist/zone'; // Included with Angular CLI.
For more information about what you can configure, see the [Zone.js](https://github.com/angular/angular/tree/master/packages/zone.js) documentation.
关于可配置内容的更多信息,请参见 [Zone.js](https://github.com/angular/angular/tree/master/packages/zone.js) 文档。
### NoopZone
`Zone` helps Angular know when to trigger change detection and let the developers focus on the application development.
By 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` 能帮助 Angular 知道何时要触发变更检测,并使开发人员专注于应用开发。默认情况下,`Zone` 已加载且无需其他配置即可工作。但是,也不是一定要用 `Zone` 才能使 Angular 工作。相反,你也可以选择自己触发变更检测。
<div class="alert is-helpful">
<h4>Disabling <code>Zone</code></h4>
<h4>禁用 <code>Zone</code></h4>
**If you disable `Zone`, you will need to trigger all change detection at the correct timing yourself, which requires comprehensive knowledge of change detection**.
**如果禁用了 `Zone`,你就要自己在正确的时间触发所有变更检测,这需要你对变更检测机制有全面的了解**。
</div>
To remove Zone.js, make the following changes.
要删除 Zone.js请进行以下更改。
1. Remove the `zone.js` import from `polyfills.ts`:
`polyfills.ts` 中移除对 `zone.js` 的导入:
```typescript
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
@ -409,6 +537,8 @@ To remove Zone.js, make the following changes.
2. Bootstrap Angular with the `noop` zone in `src/main.ts`:
`src/main.ts` 中使用 `noop` Zone 引导 Angular
```typescript
platformBrowserDynamic().bootstrapModule(AppModule, { ngZone: 'noop' })
.catch(err => console.error(err));