2803 lines
126 KiB
Plaintext
2803 lines
126 KiB
Plaintext
block includes
|
||
include ../_util-fns
|
||
- var _JavaScript = 'JavaScript';
|
||
//- Double underscore means don't escape var, use !{__var}.
|
||
- var __chaining_op = '<code>;</code> or <code>,</code>';
|
||
- var __new_op = '<code>new</code>';
|
||
- var __objectAsMap = 'object';
|
||
|
||
:marked
|
||
Our Angular application manages what the user sees and can do, achieving this through the interaction of a Component class instance (the *component*) and its user-facing template.
|
||
|
||
Angular 应用管理着用户之所见和所为,并通过 Component 类的实例(*组件*)和面向用户的模板来与用户交互。
|
||
|
||
Many of us are familiar with the component/template duality from our experience with model-view-controller (MVC) or model-view-viewmodel (MVVM). In Angular, the component plays the part of the controller/viewmodel, and the template represents the view.
|
||
|
||
从使用模型-视图-控制器 (MVC) 或模型-视图-视图模型 (MVVM) 的经验中,很多开发人员都熟悉了组件和模板这两个概念。
|
||
在 Angular 中,组件扮演着控制器或视图模型的角色,模板则扮演视图的角色。
|
||
|
||
Let’s find out what it takes to write a template for our view. We’ll cover these basic elements of template syntax:
|
||
|
||
来看看写视图的模板都需要什么。本章将覆盖模板语法中的下列基本元素:
|
||
|
||
* [HTML](#html)
|
||
|
||
[HTML](#html)
|
||
|
||
* [Interpolation](#interpolation)
|
||
|
||
[插值表达式](#interpolation)
|
||
|
||
* [Template expressions](#template-expressions)
|
||
|
||
[模板表达式](#template-expressions)
|
||
|
||
* [Template statements](#template-statements)
|
||
|
||
[模板语句](#template-statements)
|
||
|
||
* [Binding syntax](#binding-syntax)
|
||
|
||
[绑定语法](#binding-syntax)
|
||
|
||
* [Property binding](#property-binding)
|
||
|
||
[属性 (property) 绑定](#property-binding)
|
||
|
||
* [Attribute, class, and style bindings](#other-bindings)
|
||
|
||
[attribute、class 和 style 绑定](#other-bindings)
|
||
|
||
* [Event binding](#event-binding)
|
||
|
||
[事件绑定](#event-binding)
|
||
|
||
* [Two-way data binding](#two-way)
|
||
|
||
[双向数据绑定](#two-way)
|
||
|
||
* [Two-way data binding with `NgModel`](#ngModel)
|
||
|
||
[使用`NgModel`进行双向数据绑定](#ngModel)
|
||
|
||
* [Built-in directives](#directives)
|
||
|
||
[内置指令](#directives)
|
||
|
||
* [NgClass](#ngClass)
|
||
|
||
[NgClass](#ngClass)
|
||
|
||
* [NgStyle](#ngStyle)
|
||
|
||
[NgStyle](#ngStyle)
|
||
|
||
* [NgIf](#ngIf)
|
||
|
||
[NgIf](#ngIf)
|
||
|
||
* [NgSwitch](#ngSwitch)
|
||
|
||
[NgSwitch](#ngSwitch)
|
||
|
||
* [NgFor](#ngFor)
|
||
|
||
[NgFor](#ngFor)
|
||
|
||
* [* and <template>](#star-template)
|
||
|
||
[* 与 <template>](#star-template)
|
||
|
||
* [Template reference variables](#ref-vars)
|
||
|
||
[模板引用变量](#ref-vars)
|
||
|
||
* [Input and output properties](#inputs-outputs)
|
||
|
||
[输入输出属性](#inputs-outputs)
|
||
|
||
* [Template expression operators](#expression-operators)
|
||
|
||
[模板表达式操作符](#expression-operators)
|
||
|
||
* [pipe](#pipe)
|
||
|
||
[管道](#pipe)
|
||
|
||
* [safe navigation operator (?.)](#safe-navigation-operator)
|
||
|
||
[安全导航操作符 (?.)](#safe-navigation-operator)
|
||
|
||
The <live-example></live-example>
|
||
demonstrates all of the syntax and code snippets described in this chapter.
|
||
p.
|
||
<live-example>在线例子</live-example>演示了本章中描述的所有语法和代码片段。
|
||
|
||
.l-main-section
|
||
:marked
|
||
## HTML
|
||
|
||
## HTML
|
||
|
||
HTML is the language of the Angular template.
|
||
The [QuickStart](../quickstart.html) application has a template that is pure HTML:
|
||
|
||
HTML 是 Angular 模板的语言。[快速起步](../quickstart.html)应用的模板是纯 HTML 的:
|
||
|
||
code-example(language="html" escape="html").
|
||
<h1>Hello Angular</h1>
|
||
|
||
:marked
|
||
Almost all HTML syntax is valid template syntax. The `<script>` element is a notable exception; it is forbidden, eliminating the risk of script injection attacks. (In practice, `<script>` is simply ignored.)
|
||
|
||
几乎所有的 HTML 语法都是有效的模板语法。但值得注意的例外是`<script>`元素,它被禁用了,以阻止脚本注入攻击的风险。(实际上,`<script>`只是被忽略了。)
|
||
|
||
Some legal HTML doesn’t make much sense in a template. The `<html>`, `<body>`, and `<base>` elements have no useful role in our repertoire. Pretty much everything else is fair game.
|
||
|
||
有些合法的 HTML 被用在模板中是没有意义的。`<html>`、`<body>`和`<base>`元素这个舞台上中并没有扮演有用的角色。基本上所有其它的元素都被一样使用。
|
||
|
||
We can extend the HTML vocabulary of our templates with components and directives that appear as new elements and attributes. In the following sections we are going to learn how to get and set DOM (Document Object Model) values dynamically through data binding.
|
||
|
||
可以通过组件和指令来扩展模板中的 HTML 词汇。它们看上去就是新元素和属性。接下来将学习如何通过数据绑定来动态获取/设置 DOM(文档对象模型)的值。
|
||
|
||
Let’s turn to the first form of data binding — interpolation — to see how much richer template HTML can be.
|
||
|
||
数据绑定的第一种形式 —— 插值表达式 —— 展示了模板的 HTML 可以有多丰富。
|
||
|
||
.l-main-section
|
||
:marked
|
||
## Interpolation
|
||
|
||
## 插值表达式
|
||
|
||
We met the double-curly braces of interpolation, `{{` and `}}`, early in our Angular education.
|
||
|
||
在以前的 Angular 教程中,我们遇到过由双花括号括起来的插值表达式,`{{`和`}}`。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'first-interpolation')(format=".")
|
||
:marked
|
||
We use interpolation to weave calculated strings into the text between HTML element tags and within attribute assignments.
|
||
|
||
插值表达式可以把计算后的字符串插入到 HTML 元素标签内的文本或对标签的属性进行赋值。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'title+image')(format=".")
|
||
:marked
|
||
The material between the braces is often the name of a component property. Angular replaces that name with the
|
||
string value of the corresponding component property. In the example above, Angular evaluates the `title` and `heroImageUrl` properties
|
||
and "fills in the blanks", first displaying a bold application title and then a heroic image.
|
||
|
||
在括号之间的“素材”,通常是组件属性的名字。Angular 会用组件中相应属性的字符串值,替换这个名字。
|
||
上例中,Angular 计算`title`和`heroImageUrl`属性的值,并把它们填在空白处。
|
||
首先显示粗体的应用标题,然后显示英雄的图片。
|
||
|
||
More generally, the material between the braces is a **template expression** that Angular first **evaluates**
|
||
and then **converts to a string**. The following interpolation illustrates the point by adding the two numbers within braces:
|
||
|
||
一般来说,括号间的素材是一个**模板表达式**,Angular 先**对它求值**,再把它**转换成字符串**。
|
||
下列插值表达式通过把括号中的两个数字相加说明了这一点:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'sum-1')(format=".")
|
||
:marked
|
||
The expression can invoke methods of the host component, as we do here with `getVal()`:
|
||
|
||
这个表达式可以调用宿主组件的方法,就像下面用的`getVal()`:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'sum-2')(format=".")
|
||
:marked
|
||
Angular evaluates all expressions in double curly braces, converts the expression results to strings, and links them with neighboring literal strings. Finally,
|
||
it assigns this composite interpolated result to an **element or directive property**.
|
||
|
||
Angular 对所有双花括号中的表达式求值,把求值的结果转换成字符串,并把它们跟相邻的字符串字面量连接起来。最后,把这个组合出来的插值结果赋给**元素或指令的属性**。
|
||
|
||
We appear to be inserting the result between element tags and assigning it to attributes.
|
||
It's convenient to think so, and we rarely suffer for this mistake.
|
||
Though this is not exactly true. Interpolation is a special syntax that Angular converts into a
|
||
[property binding](#property-binding), and is explained below.
|
||
|
||
表面上看,我们在元素标签之间插入了结果和对标签的属性进行了赋值。
|
||
这样思考起来很方便,并且这个误解很少给我们带来麻烦。
|
||
但严格来讲,这是不对的。插值表达式是一个特殊的语法,Angular 把它转换成了[属性绑定](#property-binding),后面将会解释这一点。
|
||
|
||
But first, let's take a closer look at template expressions and statements.
|
||
|
||
讲解属性绑定之前,先深入了解一下模板表达式和模板语句。
|
||
|
||
<a id="template-expressions"></a>
|
||
.l-main-section
|
||
:marked
|
||
## Template expressions
|
||
|
||
## 模板表达式
|
||
|
||
A template **expression** produces a value.
|
||
Angular executes the expression and assigns it to a property of a binding target;
|
||
the target might be an HTML element, a component, or a directive.
|
||
|
||
模板**表达式**产生一个值。
|
||
Angular 执行这个表达式,并把它赋值给绑定目标的属性,这个绑定目标可能是 HTML 元素、组件或指令。
|
||
|
||
We put a template expression within the interpolation braces when we wrote `{{1 + 1}}`.
|
||
We’ll see template expressions again in the [property binding](#property-binding) section,
|
||
appearing in quotes to the right of the `=` symbol as in `[property]="expression"`.
|
||
|
||
当我们写`{{1 + 1}}`时,是往插值表达式的括号中放进了一个模板表达式。
|
||
在[属性绑定](#property-binding)中会再次看到模板表达式,它出现在`=`右侧的引号中,看起来像这样:`[property]="expression"`。
|
||
|
||
We write template expressions in a language that looks like #{_JavaScript}.
|
||
Many #{_JavaScript} expressions are legal template expressions, but not all.
|
||
|
||
编写模板表达式所用的语言看起来很像 JavaScript。
|
||
很多 JavaScript 表达式也是合法的模板表达式,但不是全部。
|
||
|
||
#{_JavaScript} expressions that have or promote side effects are prohibited,
|
||
including:
|
||
|
||
JavaScript 中那些具有或可能引发副作用的表达式是被禁止的,包括:
|
||
|
||
* assignments (`=`, `+=`, `-=`, ...)
|
||
|
||
赋值 (`=`, `+=`, `-=`, ...)
|
||
|
||
* !{__new_op}
|
||
|
||
`new`运算符
|
||
|
||
* chaining expressions with !{__chaining_op}
|
||
|
||
使用`;`或`,`的链式表达式
|
||
|
||
* increment and decrement operators (`++` and `--`)
|
||
|
||
自增或自减操作符 (`++`和`--`)
|
||
|
||
:marked
|
||
Other notable differences from #{_JavaScript} syntax include:
|
||
|
||
和 JavaScript语 法的其它显著不同包括:
|
||
|
||
block notable-differences
|
||
:marked
|
||
* no support for the bitwise operators `|` and `&`
|
||
|
||
不支持位运算`|`和`&`
|
||
|
||
* new [template expression operators](#expression-operators), such as `|` and `?.`
|
||
|
||
具有新的[模板表达式运算符](#expression-operators),比如`|`和`?.`
|
||
|
||
h3#expression-context Expression context
|
||
|
||
h3#expression-context 表达式上下文
|
||
|
||
block template-expressions-cannot
|
||
:marked
|
||
Perhaps more surprising, template expressions cannot refer to anything in
|
||
the global namespace. They can’t refer to `window` or `document`. They
|
||
can’t call `console.log` or `Math.max`. They are restricted to referencing
|
||
members of the expression context.
|
||
|
||
也许更让人吃惊的是,模板表达式不能引用全局命名空间中的任何东西。
|
||
不能引用`window`或`document`。不能调用`console.log`或`Math.max`。
|
||
它们被局限于只能访问来自表达式上下文中的成员。
|
||
|
||
:marked
|
||
The *expression context* is typically the **component instance**, which is
|
||
the source of binding values.
|
||
|
||
典型的*表达式上下文*就是这个**组件实例**,它是各种绑定值的来源。
|
||
|
||
When we see *title* wrapped in double-curly braces, `{{title}}`,
|
||
we know that `title` is a property of the data-bound component.
|
||
When we see *isUnchanged* in `[disabled]="isUnchanged"`,
|
||
we know we are referring to that component's `isUnchanged` property.
|
||
|
||
当看到包裹在双花括号中的 *title* (`{{title}}`) 时,我们就知道`title`是这个数据绑定组件中的一个属性。
|
||
当看到`[disabled]="isUnchanged"`中的 *isUnchanged* 时,我们就知道正在引用该组件的`isUnchanged`属性。
|
||
|
||
The component itself is usually the expression *context*, in which case
|
||
the template expression usually references that component.
|
||
|
||
通常,组件本身就是表达式的*上下文*,这种情况下,模板表达式会引用那个组件。
|
||
|
||
The expression context can include objects other than the component.
|
||
A [template reference variable](#ref-vars) is one such alternative context object.
|
||
|
||
表达式的上下文可以包括组件之外的对象。
|
||
[模板引用变量](#ref-vars)就是备选的上下文对象之一。
|
||
|
||
:marked
|
||
<a id="no-side-effects"></a>
|
||
|
||
### Expression guidelines
|
||
|
||
### 表达式指南
|
||
|
||
Template expressions can make or break an application.
|
||
Please follow these guidelines:
|
||
|
||
模板表达式能成就或毁掉一个应用。请遵循下列指南:
|
||
|
||
* [No visible side effects](#no-visible-side-effects)
|
||
|
||
[没有可见的副作用](#no-visible-side-effects)
|
||
|
||
* [Quick execution](#quick-execution)
|
||
|
||
[执行迅速](#quick-execution)
|
||
|
||
* [Simplicity](#simplicity)
|
||
|
||
[非常简单](#simplicity)
|
||
|
||
* [Idempotence](#idempotence)
|
||
|
||
[幂等性](#idempotence)
|
||
|
||
The only exceptions to these guidelines should be in specific circumstances that you thoroughly understand.
|
||
|
||
超出上面指南外的情况应该只出现在那些你确信自己已经彻底理解的特定场景中。
|
||
|
||
#### No visible side effects
|
||
|
||
#### 没有可见的副作用
|
||
|
||
A template expression should not change any application state other than the value of the
|
||
target property.
|
||
|
||
模板表达式除了目标属性的值以外,不应该改变应用的任何状态。
|
||
|
||
This rule is essential to Angular's "unidirectional data flow" policy.
|
||
We should never worry that reading a component value might change some other displayed value.
|
||
The view should be stable throughout a single rendering pass.
|
||
|
||
这条规则是 Angular “单向数据流”策略的基础。
|
||
永远不用担心读取组件值可能改变另外的显示值。
|
||
在一次单独的渲染过程中,视图应该总是稳定的。
|
||
|
||
#### Quick execution
|
||
|
||
#### 执行迅速
|
||
|
||
Angular executes template expressions more often than we think.
|
||
They can be called after every keypress or mouse move.
|
||
Expressions should finish quickly or the user experience may drag, especially on slower devices.
|
||
Consider caching values computed from other values when the computation is expensive.
|
||
|
||
Angular 执行模板表达式比我们想象的频繁。
|
||
它们可能在每一次按键或鼠标移动后被调用。
|
||
表达式应该快速结束,否则用户就会感到拖沓,特别是在较慢的设备上。
|
||
当计算代价较高时,应该考虑缓存那些从其它值计算得出的值。
|
||
|
||
#### Simplicity
|
||
|
||
#### 非常简单
|
||
|
||
Although it's possible to write quite complex template expressions, we really shouldn't.
|
||
|
||
虽然可以写出相当复杂的模板表达式,但不要那么去写。
|
||
|
||
A property name or method call should be the norm.
|
||
An occasional Boolean negation (`!`) is OK.
|
||
Otherwise, confine application and business logic to the component itself,
|
||
where it will be easier to develop and test.
|
||
|
||
常规是属性名或方法调用。偶尔的逻辑取反 (`!`) 也还凑合。
|
||
其它情况下,应在组件中实现应用和业务逻辑,使开发和测试变得更容易。
|
||
|
||
#### Idempotence
|
||
|
||
#### 幂等性
|
||
|
||
An [idempotent](https://en.wikipedia.org/wiki/Idempotence) expression is ideal because
|
||
it is free of side effects and improves Angular's change detection performance.
|
||
|
||
最好使用[幂等的](https://en.wikipedia.org/wiki/Idempotence)表达式,因为它没有副作用,并且能提升 Angular 变更检测的性能。
|
||
|
||
In Angular terms, an idempotent expression always returns *exactly the same thing* until
|
||
one of its dependent values changes.
|
||
|
||
在 Angular 的术语中,幂等的表达式应该总是返回*完全相同的东西*,直到某个依赖值发生改变。
|
||
:marked
|
||
Dependent values should not change during a single turn of the event loop.
|
||
If an idempotent expression returns a string or a number, it returns the same string or number
|
||
when called twice in a row. If the expression returns an object (including #{_an} `#{_Array}`),
|
||
it returns the same object *reference* when called twice in a row.
|
||
|
||
在单独的一次事件循环中,被依赖的值不应该改变。
|
||
如果幂等的表达式返回一个字符串或数字,连续调用它两次,也应该返回相同的字符串或数字。
|
||
如果幂等的表达式返回一个对象(包括`Date`或`Array`),连续调用它两次,也应该返回同一个对象的*引用*。
|
||
|
||
.l-main-section#template-statements
|
||
:marked
|
||
## Template statements
|
||
|
||
## 模板语句
|
||
|
||
A template **statement** responds to an **event** raised by a binding target
|
||
such as an element, component, or directive.
|
||
|
||
模板**语句**用来响应由绑定目标(如 HTML 元素、组件或指令)触发的**事件**。
|
||
|
||
We’ll see template statements in the [event binding](#event-binding) section,
|
||
appearing in quotes to the right of the `=` symbol as in `(event)="statement"`.
|
||
|
||
模板语句将在[事件绑定](#event-binding)一节看到,它出现在`=`号右侧的引号中,就像这样:`(event)="statement"`。
|
||
|
||
A template statement *has a side effect*.
|
||
It's how we update application state from user input.
|
||
There would be no point to responding to an event otherwise.
|
||
|
||
模板语句*有副作用*。
|
||
这正是用户输入更新应用状态的方式。
|
||
否则,响应事件就没有什么意义了。
|
||
|
||
.l-sub-section
|
||
:marked
|
||
Responding to events is the other side of Angular's "unidirectional data flow".
|
||
We're free to change anything, anywhere, during this turn of the event loop.
|
||
|
||
响应事件是 Angular 中“单向数据流”的另一面。
|
||
在一次事件循环中,可以随意改变任何地方的任何东西。
|
||
:marked
|
||
Like template expressions, template *statements* use a language that looks like #{_JavaScript}.
|
||
The template statement parser is different than the template expression parser and
|
||
specifically supports both basic assignment (`=`) and chaining expressions
|
||
(with !{__chaining_op}).
|
||
|
||
和模板表达式一样,模板*语句*使用的语言也像 JavaScript。
|
||
模板语句解析器和模板表达式解析器有所不同,特别之处在于它支持基本赋值 (`=`) 和表达式链 (`;`和`,`)。
|
||
|
||
However, certain #{_JavaScript} syntax is not allowed:
|
||
|
||
然而,某些 JavaScript 语法仍然是不允许的:
|
||
|
||
* !{__new_op}
|
||
|
||
`new`运算符
|
||
|
||
* increment and decrement operators, `++` and `--`
|
||
|
||
自增和自减运算符:`++`和`--`
|
||
|
||
* operator assignment, such as `+=` and `-=`
|
||
|
||
操作并赋值,例如`+=`和`-=`
|
||
|
||
* the bitwise operators `|` and `&`
|
||
|
||
位操作符`|`和`&`
|
||
|
||
* the [template expression operators](#expression-operators)
|
||
|
||
[模板表达式运算符](#expression-operators)
|
||
|
||
:marked
|
||
### Statement context
|
||
|
||
### 语句上下文
|
||
|
||
As with expressions, statements can refer only to what's in the statement context — typically the
|
||
**component instance** to which we're binding the event.
|
||
|
||
和表达式中一样,语句只能引用语句上下文中 —— 通常是正在绑定事件的那个**组件实例**。
|
||
|
||
block statement-context
|
||
:marked
|
||
Template statements cannot refer to anything in the global namespace. They
|
||
can’t refer to `window` or `document`. They can’t call `console.log` or
|
||
`Math.max`.
|
||
|
||
模板语句无法引用全局命名空间的任何东西。它们不能引用`window`或者`document`,
|
||
不能调用`console.log`或者`Math.max`。
|
||
|
||
:marked
|
||
The *onSave* in `(click)="onSave()"` is sure to be a method of the data-bound component instance.
|
||
|
||
`(click)="onSave()"`中的 *onSave* 就是数据绑定组件实例中的方法。
|
||
|
||
The statement context may include an object other than the component.
|
||
A [template reference variable](#ref-vars) is one such alternative context object.
|
||
We'll frequently see the reserved `$event` symbol in event binding statements,
|
||
representing the "message" or "payload" of the raised event.
|
||
|
||
语句上下文可以包含组件之外的对象。
|
||
[模板引用对象](#ref-vars)就是备选上下文对象之一。
|
||
在事件绑定语句中,经常会看到被保留的`$event`符号,它代表触发事件的“消息”或“有效载荷”。
|
||
|
||
### Statement guidelines
|
||
|
||
### 语句指南
|
||
|
||
As with expressions, avoid writing complex template statements.
|
||
A method call or simple property assignment should be the norm.
|
||
|
||
和表达式一样,避免写复杂的模板语句。
|
||
常规是函数调用或者属性赋值。
|
||
|
||
Now that we have a feel for template expressions and statements,
|
||
we’re ready to learn about the varieties of data binding syntax beyond interpolation.
|
||
|
||
现在,对模板表达式和语句有了一点感觉了吧。
|
||
除插值表达式外,还有各种各样的数据绑定语法,是学习它们是时候了。
|
||
|
||
.l-main-section
|
||
:marked
|
||
<a id="binding-syntax"></a>
|
||
## Binding syntax: An overview
|
||
|
||
## 绑定语法:概览
|
||
|
||
Data binding is a mechanism for coordinating what users see with application data values.
|
||
While we could push values to and pull values from HTML,
|
||
the application is easier to write, read, and maintain if we turn these chores over to a binding framework.
|
||
We simply declare bindings between binding sources and target HTML elements and let the framework do the work.
|
||
|
||
数据绑定是一种机制,用来协调用户所见和应用数据。
|
||
虽然我们能往 HTML 推送值或者从 HTML 拉取值,
|
||
但如果把这些琐事交给数据绑定框架处理,
|
||
应用会更容易编写、阅读和维护。
|
||
只要简单地在绑定源和目标 HTML 元素之间声明绑定,框架就会完成这项工作。
|
||
|
||
Angular provides many kinds of data binding, and we’ll discuss each of them in this chapter.
|
||
First we'll take a high-level view of Angular data binding and its syntax.
|
||
|
||
Angular 提供了各种各样的数据绑定,本章将逐一讨论。
|
||
首先,从高层视角来看看 Angular 数据绑定和它的语法。
|
||
|
||
We can group all bindings into three categories by the direction in which data flows.
|
||
Each category has its distinctive syntax:
|
||
|
||
根据数据流的方向,可以把所有绑定归为三类。
|
||
每一类都有它独特的语法:
|
||
table
|
||
tr
|
||
th
|
||
p Data direction
|
||
p 数据方向
|
||
th
|
||
p Syntax
|
||
p 语法
|
||
th
|
||
p Binding type
|
||
p 绑定类型
|
||
tr
|
||
td
|
||
p One-way
|
||
p 单向
|
||
p from data source
|
||
p 从数据源
|
||
p to view target
|
||
p 到视图目标
|
||
td
|
||
code-example().
|
||
{{expression}}
|
||
[target] = "expression"
|
||
bind-target = "expression"
|
||
td
|
||
p Interpolation
|
||
p 插值表达式
|
||
p Property
|
||
p Property
|
||
p Attribute
|
||
p Attribute
|
||
p Class
|
||
p 类
|
||
p Style
|
||
p 样式
|
||
tr
|
||
td
|
||
p One-way
|
||
p 单向
|
||
p from view target
|
||
p 从视图目标
|
||
p to data source
|
||
p 到数据源
|
||
td
|
||
code-example().
|
||
(target) = "statement"
|
||
on-target = "statement"
|
||
td
|
||
p Event
|
||
p 事件
|
||
tr
|
||
td
|
||
p Two-way
|
||
p 双向
|
||
td
|
||
code-example().
|
||
[(target)] = "expression"
|
||
bindon-target = "expression"
|
||
td
|
||
p Two-way
|
||
p 双向
|
||
|
||
.alert.is-important
|
||
:marked
|
||
译注:由于 HTML attribute 和 DOM property 在中文中都被翻译成了“属性”,无法区分,
|
||
而接下来的部分重点是对它们进行比较。
|
||
|
||
我们无法改变历史,因此,在本章的翻译中,保留了它们的英文形式,不加翻译,以免混淆。
|
||
本章中,如果提到“属性”的地方,一定是指 property,因为在 Angular 中,实际上很少涉及 attribute。
|
||
|
||
但在其它章节中,为简单起见,凡是能通过上下文明显区分开的,就仍统一译为“属性”,
|
||
区分不明显的,会加注英文。
|
||
|
||
:marked
|
||
Binding types other than interpolation have a **target name** to the left of the equal sign,
|
||
either surrounded by punctuation (`[]`, `()`) or preceded by a prefix (`bind-`, `on-`, `bindon-`).
|
||
|
||
除了插值表达式之外的绑定类型,在等号左边是**目标名**,
|
||
无论是包在括号中 (`[]`、`()`) 还是用前缀形式 (`bind-`、`on-`、`bindon-`) 。
|
||
|
||
What is that target? Before we can answer that question, we must challenge ourselves to look at template HTML in a new way.
|
||
|
||
什么是“目标”?在回答这个问题之前,我们必须先挑战下自我,尝试用另一种方式来审视模板中的 HTML。
|
||
|
||
### A new mental model
|
||
|
||
### 新的思维模型
|
||
|
||
With all the power of data binding and our ability to extend the HTML vocabulary
|
||
with custom markup, it is tempting to think of template HTML as *HTML Plus*.
|
||
|
||
数据绑定的威力和允许用自定义标记扩展 HTML 词汇的能力,容易误导我们把模板 HTML 当成 *HTML+*。
|
||
|
||
Well, it *is* HTML Plus.
|
||
But it’s also significantly different than the HTML we’re used to.
|
||
We really need a new mental model.
|
||
|
||
也对,它*是* HTML+。
|
||
但它也跟我们熟悉的 HTML 有着显著的不同。
|
||
我们需要一种新的思维模型。
|
||
|
||
In the normal course of HTML development, we create a visual structure with HTML elements, and
|
||
we modify those elements by setting element attributes with string constants.
|
||
|
||
在正常的 HTML 开发过程中,我们使用 HTML 元素创建视觉结构,
|
||
通过把字符串常量设置到元素的 attribute 来修改那些元素。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'img+button')(format=".")
|
||
:marked
|
||
We still create a structure and initialize attribute values this way in Angular templates.
|
||
|
||
在 Angular 模板中,我们仍使用同样的方式来创建结构和初始化 attribute 值。
|
||
|
||
Then we learn to create new elements with components that encapsulate HTML
|
||
and drop them into our templates as if they were native HTML elements.
|
||
|
||
然后,用封装了 HTML 的组件创建新元素,并把它们当作原生 HTML 元素在模板中使用。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'hero-detail-1')(format=".")
|
||
:marked
|
||
That’s HTML Plus.
|
||
|
||
这就是HTML+。
|
||
|
||
Now we start to learn about data binding. The first binding we meet might look like this:
|
||
|
||
现在开始学习数据绑定。我们碰到的第一种数据绑定看起来是这样的:
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'disabled-button-1')(format=".")
|
||
:marked
|
||
We’ll get to that peculiar bracket notation in a moment. Looking beyond it,
|
||
our intuition tells us that we’re binding to the button's `disabled` attribute and setting
|
||
it to the current value of the component’s `isUnchanged` property.
|
||
|
||
过会儿再认识那个怪异的方括号记法。直觉告诉我们,我们正在绑定按钮的`disabled` attribute。
|
||
并把它设置为组件的`isUnchanged`属性的当前值。
|
||
|
||
Our intuition is wrong! Our everyday HTML mental model is misleading us.
|
||
In fact, once we start data binding, we are no longer working with HTML *attributes*. We aren't setting attributes.
|
||
We are setting the *properties* of DOM elements, components, and directives.
|
||
|
||
但我们的直觉是错的!日常的 HTML 思维模式在误导我们。
|
||
实际上,一旦开始数据绑定,就不再跟 HTML attribute 打交道了。
|
||
这里不是设置 attribute,而是设置 DOM 元素、组件和指令的 property。
|
||
|
||
.l-sub-section
|
||
:marked
|
||
### HTML attribute vs. DOM property
|
||
|
||
### HTML attribute 与 DOM property 的对比
|
||
|
||
The distinction between an HTML attribute and a DOM property is crucial to understanding how Angular binding works.
|
||
|
||
要想理解 Angular 绑定如何工作,重点是搞清 HTML attribute 和 DOM property 之间的区别。
|
||
|
||
**Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).**
|
||
|
||
**attribute 是由 HTML 定义的。property 是由 DOM (Document Object Model) 定义的。**
|
||
|
||
* A few HTML attributes have 1:1 mapping to properties. `id` is one example.
|
||
|
||
少量 HTML attribute 和 property 之间有着 1:1 的映射,如`id`。
|
||
|
||
* Some HTML attributes don't have corresponding properties. `colspan` is one example.
|
||
|
||
有些 HTML attribute 没有对应的 property,如`colspan`。
|
||
|
||
* Some DOM properties don't have corresponding attributes. `textContent` is one example.
|
||
|
||
有些 DOM property 没有对应的 attribute,如`textContent`。
|
||
|
||
* Many HTML attributes appear to map to properties ... but not in the way we might think!
|
||
|
||
大量 HTML attribute看起来映射到了property…… 但却不像我们想的那样!
|
||
|
||
That last category can be especially confusing ... until we understand this general rule:
|
||
|
||
最后一类尤其让人困惑…… 除非我们能理解这个普遍原则:
|
||
|
||
**Attributes *initialize* DOM properties and then they are done.
|
||
Property values can change; attribute values can't.**
|
||
|
||
**attribute *初始化* DOM property,然后它们的任务就完成了。property 的值可以改变;attribute 的值不能改变。**
|
||
|
||
For example, when the browser renders `<input type="text" value="Bob">`, it creates a
|
||
corresponding DOM node with a `value` property *initialized* to "Bob".
|
||
|
||
例如,当浏览器渲染`<input type="text" value="Bob">`时,它将创建相应 DOM 节点,
|
||
其`value` property 被*初始化为* “Bob”。
|
||
|
||
When the user enters "Sally" into the input box, the DOM element `value` *property* becomes "Sally".
|
||
But the HTML `value` *attribute* remains unchanged as we discover if we ask the input element
|
||
about that attribute: `input.getAttribute('value') // returns "Bob"`
|
||
|
||
当用户在输入框中输入 “Sally” 时,DOM 元素的`value` *property* 变成了 “Sally”。
|
||
但是这个 HTML `value` *attribute* 保持不变。如果我们读取 input 元素的 attribute,就会发现确实没变:
|
||
`input.getAttribute('value') // 返回 "Bob"`。
|
||
|
||
The HTML attribute `value` specifies the *initial* value; the DOM `value` property is the *current* value.
|
||
|
||
HTML attribute `value`指定了*初始*值;DOM `value` property 是*当前*值。
|
||
|
||
The `disabled` attribute is another peculiar example. A button's `disabled` *property* is
|
||
`false` by default so the button is enabled.
|
||
When we add the `disabled` *attribute*, its presence alone initializes the button's `disabled` *property* to `true`
|
||
so the button is disabled.
|
||
|
||
`disabled` attribute 是另一个古怪的例子。按钮的`disabled` *property* 是`false`,因为默认情况下按钮是可用的。
|
||
当我们添加`disabled` *attribute* 时,只要它出现了按钮的`disabled` *property* 就初始化为`true`,于是按钮就被禁用了。
|
||
|
||
Adding and removing the `disabled` *attribute* disables and enables the button. The value of the *attribute* is irrelevant,
|
||
which is why we cannot enable a button by writing `<button disabled="false">Still Disabled</button>`.
|
||
|
||
添加或删除`disabled` *attribute*会禁用或启用这个按钮。但 *attribute* 的值无关紧要,这就是我们为什么没法通过
|
||
`<button disabled="false">仍被禁用</button>`这种写法来启用按钮。
|
||
|
||
Setting the button's `disabled` *property* (say, with an Angular binding) disables or enables the button.
|
||
The value of the *property* matters.
|
||
|
||
设置按钮的`disabled` *property*(如,通过 Angular 绑定)可以禁用或启用这个按钮。
|
||
这就是 *property* 的价值。
|
||
|
||
**The HTML attribute and the DOM property are not the same thing, even when they have the same name.**
|
||
|
||
**就算名字相同,HTML attribute 和 DOM property 也不是同一样东西。**
|
||
|
||
:marked
|
||
This is so important, we’ll say it again.
|
||
|
||
这句话很重要,得再强调一次:
|
||
|
||
**Template binding works with *properties* and *events*, not *attributes*.**
|
||
|
||
**模板绑定是通过 *property* 和*事件*来工作的,而不是 *attribute*。**
|
||
|
||
.callout.is-helpful
|
||
header A world without attributes
|
||
header 没有 attribute 的世界
|
||
:marked
|
||
In the world of Angular, the only role of attributes is to initialize element and directive state.
|
||
When we data bind, we're dealing exclusively with element and directive properties and events.
|
||
Attributes effectively disappear.
|
||
|
||
在 Angular 的世界中,attribute 唯一的作用是用来初始化元素和指令的状态。
|
||
当进行数据绑定时,只是在与元素和指令的 property 和事件打交道,而 attribute 就完全靠边站了。
|
||
:marked
|
||
With this model firmly in mind, let's learn about binding targets.
|
||
|
||
把这个思维模型牢牢的印在脑子里,接下来,学习什么是绑定目标。
|
||
|
||
### Binding targets
|
||
|
||
### 绑定目标
|
||
|
||
The **target of a data binding** is something in the DOM.
|
||
Depending on the binding type, the target can be an
|
||
(element | component | directive) property, an
|
||
(element | component | directive) event, or (rarely) an attribute name.
|
||
The following table summarizes:
|
||
|
||
**数据绑定的目标**是 DOM 中的某些东西。
|
||
这个目标可能是(元素 | 组件 | 指令的)property、(元素 | 组件 | 指令的)事件,或(极少数情况下) attribute 名。
|
||
下面是的汇总表:
|
||
|
||
//- If you update this table, UPDATE it in Dart & JS, too.
|
||
<div width="90%">
|
||
table
|
||
tr
|
||
th
|
||
p Binding type
|
||
p 绑定类型
|
||
th
|
||
p Target
|
||
p 目标
|
||
th
|
||
p Examples
|
||
p 范例
|
||
tr
|
||
td
|
||
p Property
|
||
p Property
|
||
td
|
||
p Element property
|
||
p 元素的 property
|
||
p Component property
|
||
p 组件的 property
|
||
p Directive property
|
||
p 指令的 property
|
||
td
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-syntax-1')(format=".")
|
||
tr
|
||
td
|
||
p Event
|
||
p 事件
|
||
td
|
||
p Element event
|
||
p 元素的事件
|
||
p Component event
|
||
p 组件的事件
|
||
p Directive event
|
||
p 指令的事件
|
||
td
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-syntax-1')(format=".")
|
||
tr
|
||
td
|
||
p Two-way
|
||
p 双向
|
||
td
|
||
p Event and property
|
||
p 事件与 property
|
||
td
|
||
+makeExample('template-syntax/ts/app/app.component.html', '2-way-binding-syntax-1')(format=".")
|
||
tr
|
||
td Attribute
|
||
td
|
||
p Attribute (the exception)
|
||
p attribute(例外情况)
|
||
td
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'attribute-binding-syntax-1')(format=".")
|
||
tr
|
||
td
|
||
p Class
|
||
p CSS 类
|
||
td
|
||
p <code>class</code> property
|
||
td
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'class-binding-syntax-1')(format=".")
|
||
tr
|
||
td
|
||
p Style
|
||
p 样式
|
||
td
|
||
p <code>style</code> property
|
||
td
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'style-binding-syntax-1')(format=".")
|
||
</div>
|
||
|
||
:marked
|
||
Let’s descend from the architectural clouds and look at each of these binding types in concrete detail.
|
||
|
||
让我们从结构性云层中走出来,看看每种绑定类型的具体情况。
|
||
|
||
.l-main-section
|
||
:marked
|
||
## Property binding
|
||
|
||
## 属性 (property) 绑定
|
||
|
||
We write a template **property binding** when we want to set a property of a view element to the value of
|
||
a [template expression](#template-expressions).
|
||
|
||
当要把视图元素的属性 (property) 设置为[模板表达式](#template-expressions)时,就要写模板的**属性 (property) 绑定**。
|
||
|
||
The most common property binding sets an element property to a component property value. An example is
|
||
binding the `src` property of an image element to a component’s `heroImageUrl` property:
|
||
|
||
最常用的属性绑定是把元素属性设置为组件属性的值。
|
||
下面这个例子中,image 元素的`src`属性会被绑定到组件的`heroImageUrl`属性上:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-1')(format=".")
|
||
:marked
|
||
Another example is disabling a button when the component says that it `isUnchanged`:
|
||
|
||
另一个例子是当组件说它`isUnchanged`(未改变)时禁用按钮:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-2')(format=".")
|
||
:marked
|
||
Another is setting a property of a directive:
|
||
|
||
另一个例子是设置指令的属性:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-3')(format=".")
|
||
:marked
|
||
Yet another is setting the model property of a custom component (a great way
|
||
for parent and child components to communicate):
|
||
|
||
还有另一个例子是设置自定义组件的模型属性(这是父子组件之间通讯的重要途径):
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-4')(format=".")
|
||
:marked
|
||
### One-way *in*
|
||
|
||
### 单向*输入*
|
||
|
||
People often describe property binding as *one-way data binding* because it flows a value in one direction,
|
||
from a component’s data property into a target element property.
|
||
|
||
人们经常把属性绑定描述成*单向数据绑定*,因为值的流动是单向的,从组件的数据属性流动到目标元素的属性。
|
||
|
||
We cannot use property binding to pull values *out* of the target element.
|
||
We can't bind to a property of the target element to read it. We can only set it.
|
||
|
||
不能使用属性绑定来从目标元素拉取值,也不能绑定到目标元素的属性来读取它。只能设置它。
|
||
|
||
.l-sub-section
|
||
:marked
|
||
Nor can we use property binding to *call* a method on the target element.
|
||
|
||
也不能使用属性绑定来*调用*目标元素上的方法。
|
||
|
||
If the element raises events we can listen to them with an [event binding](#event-binding).
|
||
|
||
如果这个元素触发了事件,可以通过[事件绑定](#event-binding)来监听它们。
|
||
|
||
If we must read a target element property or call one of its methods,
|
||
we'll need a different technique.
|
||
See the API reference for
|
||
[ViewChild](../api/core/index/ViewChild-decorator.html) and
|
||
[ContentChild](../api/core/index/ContentChild-decorator.html).
|
||
|
||
如果必须读取目标元素上的属性或调用它的某个方法,得用另一种技术。
|
||
参见 API 参考手册中的 [ViewChild](../api/core/index/ViewChild-var.html) 和 [ContentChild](../api/core/index/ContentChild-var.html)。
|
||
|
||
:marked
|
||
### Binding target
|
||
|
||
### 绑定目标
|
||
|
||
An element property between enclosing square brackets identifies the target property. The target property in the following code is the image element’s `src` property.
|
||
|
||
包裹在方括号中的元素属性名标记着目标属性。下列代码中的目标属性是 image 元素的`src`属性。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-1')(format=".")
|
||
:marked
|
||
Some people prefer the `bind-` prefix alternative, known as the *canonical form*:
|
||
|
||
有些人喜欢用`bind-`前缀的可选形式,并称之为*规范形式*:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-5')(format=".")
|
||
:marked
|
||
The target name is always the name of a property, even when it appears to be the name of something else. We see `src` and may think it’s the name of an attribute. No. It’s the name of an image element property.
|
||
|
||
目标的名字总是 property 的名字。即使它看起来和别的名字一样。
|
||
看到`src`时,可能会把它当做 attribute。不!它不是!它是 image 元素的 property 名。
|
||
|
||
Element properties may be the more common targets,
|
||
but Angular looks first to see if the name is a property of a known directive,
|
||
as it is in the following example:
|
||
|
||
元素属性可能是最常见的绑定目标,但 Angular 会先去看这个名字是否是某个已知指令的属性名,就像下面的例子中一样:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-3')(format=".")
|
||
|
||
.l-sub-section
|
||
:marked
|
||
Technically, Angular is matching the name to a directive [input](#inputs-outputs),
|
||
one of the property names listed in the directive’s `inputs` array or a property decorated with `@Input()`.
|
||
Such inputs map to the directive’s own properties.
|
||
|
||
严格来说,Angular 正在匹配指令的[输入属性](#inputs-outputs)的名字。
|
||
这个名字是指令的`inputs`数组中所列的名字,或者是带有`@Input()`装饰器的属性。
|
||
这些输入属性被映射为指令自己的属性。
|
||
:marked
|
||
If the name fails to match a property of a known directive or element, Angular reports an “unknown directive” error.
|
||
|
||
如果名字没有匹配上已知指令或元素的属性,Angular 就会报告“未知指令”的错误。
|
||
|
||
### Avoid side effects
|
||
|
||
### 消除副作用
|
||
|
||
As we've already discussed, evaluation of a template expression should have no visible side effects. The expression language itself does its part to keep us safe. We can’t assign a value to anything in a property binding expression nor use the increment and decrement operators.
|
||
|
||
正如曾讨论过的,模板表达式的计算不能有可见的副作用。表达式语言本身可以提供一部分安全保障。
|
||
不能在属性绑定表达式中对任何东西赋值,也不能使用自增、自减运算符。
|
||
|
||
Of course, our expression might invoke a property or method that has side effects. Angular has no way of knowing that or stopping us.
|
||
|
||
当然,表达式可能会调用具有副作用的属性或方法。但 Angular 没法知道这一点,也没法阻止我们。
|
||
|
||
The expression could call something like `getFoo()`. Only we know what `getFoo()` does.
|
||
If `getFoo()` changes something and we happen to be binding to that something, we risk an unpleasant experience. Angular may or may not display the changed value. Angular may detect the change and throw a warning error. Our general advice: stick to data properties and to methods that return values and do no more.
|
||
|
||
表达式中可以调用像`getFoo()`这样的方法。只有我们知道`getFoo()`干了什么。
|
||
如果`getFoo()`改变了某个东西,恰好又绑定到个这个东西,我们就可能把自己坑了。
|
||
Angular 可能显示也可能不显示变化后的值。Angular 还可能检测到变化,并抛出警告型错误。
|
||
一般建议是,只绑定数据属性和那些只返回值而不做其它事情的方法。
|
||
|
||
### Return the proper type
|
||
|
||
### 返回恰当的类型
|
||
|
||
The template expression should evaluate to the type of value expected by the target property.
|
||
Return a string if the target property expects a string.
|
||
Return a number if the target property expects a number.
|
||
Return an object if the target property expects an object.
|
||
|
||
模板表达式应该返回目标属性所需类型的值。
|
||
如果目标属性想要个字符串,就返回字符串。
|
||
如果目标属性想要个数字,就返回数字。
|
||
如果目标属性想要个对象,就返回对象。
|
||
|
||
The `hero` property of the `HeroDetail` component expects a `Hero` object, which is exactly what we’re sending in the property binding:
|
||
|
||
`HeroDetail`组件的`hero`属性想要一个`Hero`对象,那就在属性绑定中精确地给它一个`Hero`对象:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-4')(format=".")
|
||
|
||
block dart-type-exceptions
|
||
//- N/A
|
||
|
||
:marked
|
||
### Remember the brackets
|
||
|
||
### 别忘了方括号
|
||
|
||
The brackets tell Angular to evaluate the template expression.
|
||
If we forget the brackets, Angular treats the string as a constant and *initializes the target property* with that string.
|
||
It does *not* evaluate the string!
|
||
|
||
方括号告诉 Angular 要计算模板表达式。
|
||
如果忘了加方括号,Angular 会把这个表达式当做字符串常量看待,并用该字符串来*初始化目标属性*。
|
||
它*不会*计算这个字符串。
|
||
|
||
Don't make the following mistake:
|
||
|
||
不要出现这样的失误:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-6')(format=".")
|
||
|
||
block dart-type-exception-example
|
||
//- N/A
|
||
|
||
a(id="one-time-initialization")
|
||
:marked
|
||
### One-time string initialization
|
||
|
||
### 一次性字符串初始化
|
||
|
||
We *should* omit the brackets when all of the following are true:
|
||
|
||
当下列条件满足时,*应该*省略括号:
|
||
* The target property accepts a string value.
|
||
|
||
目标属性接受字符串值。
|
||
|
||
* The string is a fixed value that we can bake into the template.
|
||
|
||
字符串是个固定值,可以直接合并到模块中。
|
||
|
||
* This initial value never changes.
|
||
|
||
这个初始值永不改变。
|
||
|
||
We routinely initialize attributes this way in standard HTML, and it works
|
||
just as well for directive and component property initialization.
|
||
The following example initializes the `prefix` property of the `HeroDetailComponent` to a fixed string,
|
||
not a template expression. Angular sets it and forgets about it.
|
||
|
||
我们经常这样在标准 HTML 中用这种方式初始化 attribute,这种方式也可以用在初始化指令和组件的属性。
|
||
下面这个例子把`HeroDetailComponent`的`prefix`属性初始化为固定的字符串,而不是模板表达式。Angular 设置它,然后忘记它。
|
||
// #enddocregion property-binding-12
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-7')(format=".")
|
||
:marked
|
||
The `[hero]` binding, on the other hand, remains a live binding to the component's `currentHero` property.
|
||
|
||
作为对比,`[hero]`绑定是组件的`currentHero`属性的活绑定,它会一直随着更新。
|
||
|
||
### Property binding or interpolation?
|
||
|
||
### 属性绑定还是插值表达式?
|
||
|
||
We often have a choice between interpolation and property binding.
|
||
The following binding pairs do the same thing:
|
||
|
||
我们通常得在插值表达式和属性绑定之间做出选择。
|
||
下列这几对绑定做的事情完全相同:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-vs-interpolation')(format=".")
|
||
:marked
|
||
Interpolation is a convenient alternative for property binding in many cases.
|
||
In fact, Angular translates those interpolations into the corresponding property bindings
|
||
before rendering the view.
|
||
|
||
在多数情况下,插值表达式是更方便的备选项。
|
||
实际上,在渲染视图之前,Angular 把这些插值表达式翻译成相应的属性绑定。
|
||
|
||
There is no technical reason to prefer one form to the other.
|
||
We lean toward readability, which tends to favor interpolation.
|
||
We suggest establishing coding style rules and choosing the form that
|
||
both conforms to the rules and feels most natural for the task at hand.
|
||
|
||
没有技术上的理由能决定哪种形式更好。
|
||
我们倾向于可读性,所以倾向于插值表达式。
|
||
建议建立代码风格规则,选择一种形式,
|
||
这样,既遵循了规则,又能让手头的任务做起来更自然。
|
||
|
||
:marked
|
||
#### Content security
|
||
|
||
#### 内容安全
|
||
|
||
Imagine the following *malicious content*.
|
||
|
||
假设下面的*恶毒内容*
|
||
+makeExample('template-syntax/ts/app/app.component.ts', 'evil-title')(format=".")
|
||
:marked
|
||
Fortunately, Angular data binding is on alert for dangerous HTML.
|
||
It *sanitizes* the values before displaying them.
|
||
It **will not** allow HTML with script tags to leak into the browser, neither with interpolation
|
||
nor property binding.
|
||
|
||
幸运的是,Angular 数据绑定对危险 HTML 有防备。
|
||
在显示它们之前,它对内容先进行*消毒*。
|
||
不管是插值表达式还是属性绑定,都**不会**允许带有 script 标签的 HTML 泄漏到浏览器中。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'property-binding-vs-interpolation-sanitization')(format=".")
|
||
:marked
|
||
Interpolation handles the script tags differently than property binding but both approaches render the
|
||
content harmlessly.
|
||
|
||
插值表达式处理 script 标签与属性绑定有所不同,但是二者都只渲染没有危害的内容。
|
||
figure.image-display
|
||
img(src='/resources/images/devguide/template-syntax/evil-title.png' alt="evil title made safe" width='500px')
|
||
|
||
.l-main-section
|
||
:marked
|
||
<a id="other-bindings"></a>
|
||
## Attribute, class, and style bindings
|
||
|
||
## attribute、class 和 style 绑定
|
||
|
||
The template syntax provides specialized one-way bindings for scenarios less well suited to property binding.
|
||
|
||
模板语法为那些不太适合使用属性绑定的场景提供了专门的单向数据绑定形式。
|
||
|
||
### Attribute binding
|
||
|
||
### attribute 绑定
|
||
|
||
We can set the value of an attribute directly with an **attribute binding**.
|
||
|
||
可以通过**attribute 绑定**来直接设置 attribute 的值。
|
||
.l-sub-section
|
||
:marked
|
||
This is the only exception to the rule that a binding sets a target property. This is the only binding that creates and sets an attribute.
|
||
|
||
这是“绑定到目标属性 (property)”这条规则中唯一的例外。这是唯一的能创建和设置 attribute 的绑定形式。
|
||
|
||
:marked
|
||
We have stressed throughout this chapter that setting an element property with a property binding is always preferred to setting the attribute with a string. Why does Angular offer attribute binding?
|
||
|
||
本章中,通篇都在说通过属性绑定来设置元素的属性总是好于用字符串设置 attribute。为什么 Angular 还提供了 attribute 绑定呢?
|
||
|
||
**We must use attribute binding when there is no element property to bind.**
|
||
|
||
**因为当元素没有属性可绑的时候,就必须使用 attribute 绑定。**
|
||
|
||
Consider the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA),
|
||
[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG), and
|
||
table span attributes. They are pure attributes.
|
||
They do not correspond to element properties, and they do not set element properties.
|
||
There are no property targets to bind to.
|
||
|
||
考虑 [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA),
|
||
[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG) 和 table 中的 colspan/rowspan 等 attribute。
|
||
它们是纯粹的 attribute,没有对应的属性可供绑定。
|
||
|
||
We become painfully aware of this fact when we try to write something like this:
|
||
|
||
如果想写出类似下面这样的东西,现状会令我们痛苦:
|
||
code-example(language="html").
|
||
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
|
||
:marked
|
||
We get this error:
|
||
|
||
会得到这个错误:
|
||
code-example(format="nocode").
|
||
Template parse errors:
|
||
Can't bind to 'colspan' since it isn't a known native property
|
||
|
||
模板解析错误:不能绑定到 'colspan',因为它不是已知的原生属性
|
||
:marked
|
||
As the message says, the `<td>` element does not have a `colspan` property.
|
||
It has the "colspan" *attribute*, but
|
||
interpolation and property binding can set only *properties*, not attributes.
|
||
|
||
正如提示中所说,`<td>`元素没有`colspan`属性。
|
||
但是插值表达式和属性绑定只能设置*属性*,不能设置 attribute。
|
||
|
||
We need attribute bindings to create and bind to such attributes.
|
||
|
||
我们需要 attribute 绑定来创建和绑定到这样的 attribute。
|
||
|
||
Attribute binding syntax resembles property binding.
|
||
Instead of an element property between brackets, we start with the prefix **`attr`**,
|
||
followed by a dot (`.`) and the name of the attribute. We then set the attribute
|
||
value, using an expression that resolves to a string.
|
||
|
||
attribute 绑定的语法与属性绑定类似。
|
||
但方括号中的部分不是元素的属性名,而是由**`attr`**前缀,一个点 (`.`) 和 attribute 的名字组成。
|
||
可以通过值为字符串的表达式来设置 attribute 的值。
|
||
|
||
Here we bind `[attr.colspan]` to a calculated value:
|
||
|
||
这里把`[attr.colspan]`绑定到一个计算值:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'attrib-binding-colspan')(format=".")
|
||
:marked
|
||
Here's how the table renders:
|
||
|
||
这里是表格渲染出来的样子:
|
||
|
||
<table border="1px">
|
||
<tr><td colspan="2">One-Two</td></tr>
|
||
<tr><td>Five</td><td>Six</td></tr>
|
||
</table>
|
||
|
||
One of the primary use cases for attribute binding
|
||
is to set ARIA attributes, as in this example:
|
||
|
||
attribute 绑定的主要用例之一是设置 ARIA attribute(译注:ARIA指可访问性,用于给残障人士访问互联网提供便利),
|
||
就像这个例子中一样:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'attrib-binding-aria')(format=".")
|
||
:marked
|
||
### Class binding
|
||
|
||
### CSS 类绑定
|
||
|
||
We can add and remove CSS class names from an element’s `class` attribute with
|
||
a **class binding**.
|
||
|
||
借助 **CSS 类绑定**,可以从元素的`class` attribute 上添加和移除 CSS 类名。
|
||
|
||
Class binding syntax resembles property binding.
|
||
Instead of an element property between brackets, we start with the prefix `class`,
|
||
optionally followed by a dot (`.`) and the name of a CSS class: `[class.class-name]`.
|
||
|
||
CSS 类绑定绑定的语法与属性绑定类似。
|
||
但方括号中的部分不是元素的属性名,而是由**`class`**前缀,一个点 (`.`)和 CSS 类的名字组成,
|
||
其中后两部分是可选的。形如:`[class.class-name]`。
|
||
|
||
The following examples show how to add and remove the application's "special" class
|
||
with class bindings. Here's how we set the attribute without binding:
|
||
|
||
下列例子示范了如何通过 CSS 类绑定来添加和移除应用的 "special" 类。不用绑定直接设置 attribute 时是这样的:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'class-binding-1')(format=".")
|
||
:marked
|
||
We can replace that with a binding to a string of the desired class names; this is an all-or-nothing, replacement binding.
|
||
|
||
可以把它改写为绑定到所需 CSS 类名的绑定;这是一个或者全有或者全无的替换型绑定。
|
||
(译注:即当 badCurly 有值时 class 这个 attribute 设置的内容会被完全覆盖)
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'class-binding-2')(format=".")
|
||
|
||
:marked
|
||
Finally, we can bind to a specific class name.
|
||
Angular adds the class when the template expression evaluates to #{_truthy}.
|
||
It removes the class when the expression is #{_falsey}.
|
||
|
||
最后,可以绑定到特定的类名。
|
||
当模板表达式的求值结果是真值时,Angular 会添加这个类,反之则移除它。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'class-binding-3')(format=".")
|
||
|
||
.l-sub-section
|
||
:marked
|
||
While this is a fine way to toggle a single class name,
|
||
we generally prefer the [NgClass directive](#ngClass) for managing multiple class names at the same time.
|
||
|
||
虽然这是切换单一类名的好办法,但我们通常更喜欢使用 [NgClass指令](#ngClass) 来同时管理多个类名。
|
||
|
||
:marked
|
||
### Style binding
|
||
|
||
### 样式绑定
|
||
|
||
We can set inline styles with a **style binding**.
|
||
|
||
通过**样式绑定**,可以设置内联样式。
|
||
|
||
Style binding syntax resembles property binding.
|
||
Instead of an element property between brackets, we start with the prefix `style`,
|
||
followed by a dot (`.`) and the name of a CSS style property: `[style.style-property]`.
|
||
|
||
样式绑定的语法与属性绑定类似。
|
||
但方括号中的部分不是元素的属性名,而由**`style`**前缀,一个点 (`.`)和 CSS 样式的属性名组成。
|
||
形如:`[style.style-property]`。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'style-binding-1')(format=".")
|
||
:marked
|
||
Some style binding styles have unit extension. Here we conditionally set the font size in “em” and “%” units .
|
||
|
||
有些样式绑定中的样式带有单位。在这里,以根据条件用 “em” 和 “%” 来设置字体大小的单位。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'style-binding-2')(format=".")
|
||
|
||
.l-sub-section
|
||
:marked
|
||
While this is a fine way to set a single style,
|
||
we generally prefer the [NgStyle directive](#ngStyle) when setting several inline styles at the same time.
|
||
|
||
虽然这是设置单一样式的好办法,但我们通常更喜欢使用 [NgStyle指令](#ngStyle) 来同时设置多个内联样式。
|
||
|
||
.l-sub-section
|
||
:marked
|
||
Note that a _style property_ name can be written in either
|
||
[dash-case](glossary.html#dash-case), as shown above, or
|
||
[camelCase](glossary.html#camelcase), such as `fontSize`.
|
||
|
||
注意,_样式属性_命名方法可以用[中线命名法](glossary.html#dash-case),像上面的一样
|
||
也可以用[驼峰式命名法](glossary.html#camelcase),如`fontSize`。
|
||
|
||
block style-property-name-dart-diff
|
||
//- N/A
|
||
|
||
.l-main-section
|
||
:marked
|
||
## Event binding
|
||
|
||
## 事件绑定
|
||
|
||
The bindings we’ve met so far flow data in one direction: **from a component to an element**.
|
||
|
||
前面遇到的绑定的数据流都是单向的:**从组件到元素**。
|
||
|
||
Users don’t just stare at the screen. They enter text into input boxes. They pick items from lists.
|
||
They click buttons. Such user actions may result in a flow of data in the opposite direction:
|
||
**from an element to a component**.
|
||
|
||
用户不会只盯着屏幕看。它们会在输入框中输入文本。它们会从列表中选取条目。
|
||
它们会点击按钮。这类用户动作可能导致反向的数据流:*从元素到组件*。
|
||
|
||
The only way to know about a user action is to listen for certain events such as
|
||
keystrokes, mouse movements, clicks, and touches.
|
||
We declare our interest in user actions through Angular event binding.
|
||
|
||
知道用户动作的唯一方式是监听某些事件,如按键、鼠标移动、点击和触摸屏幕。
|
||
可以通过 Angular 事件绑定来声明对哪些用户动作感兴趣。
|
||
|
||
Event binding syntax consists of a **target event** within parentheses on the left of an equal sign, and a quoted
|
||
[template statement](#template-statements) on the right.
|
||
The following event binding listens for the button’s click event, calling
|
||
the component's `onSave()` method whenever a click occurs:
|
||
|
||
事件绑定语法由等号左侧带圆括号的**目标事件**和右侧引号中的[模板语句](#template-statements)组成。
|
||
下面事件绑定监听按钮的点击事件。每当点击发生时,都会调用组件的`onSave()`方法。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-1')(format=".")
|
||
|
||
:marked
|
||
### Target event
|
||
|
||
### 目标事件
|
||
|
||
A **name between parentheses** — for example, `(click)` —
|
||
identifies the target event. In the following example, the target is the button’s click event.
|
||
|
||
**圆括号中的名称** —— 比如`(click)` —— 标记出目标事件。在下面例子中,目标是按钮的 click 事件。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-1')(format=".")
|
||
:marked
|
||
Some people prefer the `on-` prefix alternative, known as the **canonical form**:
|
||
|
||
有些人更喜欢带`on-`前缀的备选形式,称之为**规范形式**:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-2')(format=".")
|
||
:marked
|
||
Element events may be the more common targets, but Angular looks first to see if the name matches an event property
|
||
of a known directive, as it does in the following example:
|
||
|
||
元素事件可能是更常见的目标,但 Angular 会先看这个名字是否能匹配上已知指令的事件属性,就像下面这个例子:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-3')(format=".")
|
||
|
||
.l-sub-section
|
||
:marked
|
||
The `myClick` directive is further described in the section
|
||
on [aliasing input/output properties](#aliasing-io).
|
||
|
||
更多关于该`myClick`指令的解释,见[给输入/输出属性起别名](#aliasing-io)。
|
||
:marked
|
||
If the name fails to match an element event or an output property of a known directive,
|
||
Angular reports an “unknown directive” error.
|
||
|
||
如果这个名字没能匹配到元素事件或已知指令的输出属性,Angular 就会报“未知指令”错误。
|
||
|
||
### *$event* and event handling statements
|
||
|
||
### *$event* 和事件处理语句
|
||
|
||
In an event binding, Angular sets up an event handler for the target event.
|
||
|
||
在事件绑定中,Angular 会为目标事件设置事件处理器。
|
||
|
||
When the event is raised, the handler executes the template statement.
|
||
The template statement typically involves a receiver, which performs an action
|
||
in response to the event, such as storing a value from the HTML control
|
||
into a model.
|
||
|
||
当事件发生时,这个处理器会执行模板语句。
|
||
典型的模板语句通常涉及到响应事件执行动作的接收器,例如从 HTML 控件中取得值,并存入模型。
|
||
|
||
The binding conveys information about the event, including data values, through
|
||
an **event object named `$event`**.
|
||
|
||
绑定会通过**名叫`$event`的事件对象**传递关于此事件的信息(包括数据值)。
|
||
|
||
The shape of the event object is determined by the target event.
|
||
If the target event is a native DOM element event, then `$event` is a
|
||
[DOM event object]( https://developer.mozilla.org/en-US/docs/Web/Events),
|
||
with properties such as `target` and `target.value`.
|
||
|
||
事件对象的形态取决于目标事件。如果目标事件是原生 DOM 元素事件,
|
||
`$event`就是 [DOM事件对象]( https://developer.mozilla.org/en-US/docs/Web/Events),它有像`target`和`target.value`这样的属性。
|
||
|
||
Consider this example:
|
||
|
||
考虑这个范例:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'without-NgModel')(format=".")
|
||
:marked
|
||
This code sets the input box `value` property by binding to the `firstName` property. To listen for changes to the value, the code binds to the input box's `input` event.
|
||
When the user makes changes, the `input` event is raised, and the binding executes the statement within a context that includes the DOM event object, `$event`.
|
||
|
||
上面的代码在把输入框的`value`属性绑定到`firstName`属性。
|
||
要监听对值的修改,代码绑定到输入框的`input`事件。
|
||
当用户造成更改时,`input`事件被触发,并在包含了 DOM 事件对象 (`$event`) 的上下文中执行这条语句。
|
||
|
||
To update the `firstName` property, the changed text is retrieved by following the path `$event.target.value`.
|
||
|
||
要更新`firstName`属性,就要通过路径`$event.target.value`来获取更改后的值。
|
||
|
||
If the event belongs to a directive (recall that components are directives), `$event` has whatever shape the directive decides to produce.
|
||
|
||
如果事件属于指令(回想一下,组件是指令的一种),那么`$event`具体是什么由指令决定。
|
||
|
||
<a id="eventemitter"></a>
|
||
<a id="custom-event"></a>
|
||
### Custom events with *EventEmitter*
|
||
|
||
### 使用 *EventEmitter* 实现自定义事件
|
||
|
||
Directives typically raise custom events with an Angular [EventEmitter](../api/core/index/EventEmitter-class.html).
|
||
The directive creates an `EventEmitter` and exposes it as a property.
|
||
The directive calls `EventEmitter.emit(payload)` to fire an event, passing in a message payload, which can be anything.
|
||
Parent directives listen for the event by binding to this property and accessing the payload through the `$event` object.
|
||
|
||
通常,指令使用 Angular [EventEmitter](../api/core/index/EventEmitter-class.html) 来触发自定义事件。
|
||
指令创建一个`EventEmitter`实例,并且把它作为属性暴露出来。
|
||
指令调用`EventEmitter.emit(payload)`来触发事件,可以传入任何东西作为消息载荷。
|
||
父指令通过绑定到这个属性来监听事件,并通过`$event`对象来访问载荷。
|
||
|
||
Consider a `HeroDetailComponent` that presents hero information and responds to user actions.
|
||
Although the `HeroDetailComponent` has a delete button it doesn't know how to delete the hero itself.
|
||
The best it can do is raise an event reporting the user's delete request.
|
||
|
||
假设`HeroDetailComponent`用于显示英雄的信息,并响应用户的动作。
|
||
虽然`HeroDetailComponent`包含删除按钮,但它自己并不知道该如何删除这个英雄。
|
||
最好的做法是触发事件来报告“删除用户”的请求。
|
||
|
||
Here are the pertinent excerpts from that `HeroDetailComponent`:
|
||
|
||
下面的代码节选自`HeroDetailComponent`:
|
||
+makeExample('template-syntax/ts/app/hero-detail.component.ts',
|
||
'template-1', 'HeroDetailComponent.ts (模板)')(format=".")
|
||
+makeExample('template-syntax/ts/app/hero-detail.component.ts',
|
||
'deleteRequest', 'HeroDetailComponent.ts (删除逻辑)')(format=".")
|
||
|
||
:marked
|
||
The component defines a `deleteRequest` property that returns an `EventEmitter`.
|
||
When the user clicks *delete*, the component invokes the `delete()` method,
|
||
telling the `EventEmitter` to emit a `Hero` object.
|
||
|
||
组件定义了`deleteRequest`属性,它是`EventEmitter`实例。
|
||
当用户点击*删除*时,组件会调用`delete()`方法,让`EventEmitter`发出一个`Hero`对象。
|
||
|
||
Now imagine a hosting parent component that binds to the `HeroDetailComponent`'s `deleteRequest` event.
|
||
|
||
现在,假设有个宿主的父组件,它绑定了`HeroDetailComponent`的`deleteRequest`事件。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html',
|
||
'event-binding-to-component')(format=".")
|
||
:marked
|
||
When the `deleteRequest` event fires, Angular calls the parent component's `deleteHero` method,
|
||
passing the *hero-to-delete* (emitted by `HeroDetail`) in the `$event` variable.
|
||
|
||
当`deleteRequest`事件触发时,Angular 调用父组件的`deleteHero`方法,
|
||
在`$event`变量中传入*要删除的英雄*(来自`HeroDetail`)。
|
||
|
||
### Template statements have side effects
|
||
|
||
### 模板语句有副作用
|
||
|
||
The `deleteHero` method has a side effect: it deletes a hero.
|
||
Template statement side effects are not just OK, but expected.
|
||
|
||
`deleteHero`方法有副作用:它删除了一个英雄。
|
||
模板语句的副作用不仅没问题,反而正是所期望的。
|
||
|
||
Deleting the hero updates the model, perhaps triggering other changes
|
||
including queries and saves to a remote server.
|
||
These changes percolate through the system and are ultimately displayed in this and other views.
|
||
|
||
删除这个英雄会更新模型,还可能触发其它修改,包括向远端服务器的查询和保存。
|
||
这些变更通过系统进行扩散,并最终显示到当前以及其它视图中。
|
||
|
||
//-
|
||
:marked
|
||
### Event bubbling and propagation [TODO: reinstate this section when it becomes true]
|
||
Angular invokes the event-handling statement if the event is raised by the current element or one of its child elements.
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-bubbling')(format=".")
|
||
:marked
|
||
Many DOM events, both [native](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Overview_of_Events_and_Handlers ) and [custom](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events ), bubble up their ancestor tree of DOM elements until an event handler along the way prevents further propagation.
|
||
|
||
.l-sub-section
|
||
:marked
|
||
`EventEmitter` events don’t bubble.
|
||
|
||
:marked
|
||
The result of an event binding statement determines whether
|
||
[event propagation](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Examples#Example_5:_Event_Propagation)
|
||
continues or stops with the current element.
|
||
|
||
Event propagation stops if the binding statement returns a falsey value (as does a method with no return value).
|
||
Clicking the button in the next example triggers a save;
|
||
the click doesn't make it to the outer `<div>` so the div's save handler is not called.
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-no-propagation')(format=".")
|
||
:marked
|
||
Propagation continues if the statement returns a truthy value. In the next example, the click is heard by both the button
|
||
and the outer `<div>`, causing a double save.
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-propagation')(format=".")
|
||
|
||
#two-way
|
||
.l-main-section
|
||
:marked
|
||
## Two-way binding
|
||
|
||
## 双向数据绑定
|
||
|
||
We often want to both display a data property and update that property when the user makes changes.
|
||
|
||
我们经常需要显示数据属性,并在用户作出更改时更新该属性。
|
||
|
||
On the element side that takes a combination of setting a specific element property
|
||
and listening for an element change event.
|
||
|
||
在元素层面上,既要设置元素属性,又要监听元素事件变化。
|
||
|
||
Angular offers a special _two-way data binding_ syntax for this purpose, **`[(x)]`**.
|
||
The `[(x)]` syntax combines the brackets
|
||
of _property binding_, `[x]`, with the parentheses of _event binding_, `(x)`.
|
||
|
||
Angular 为此提供一种特殊的_双向数据绑定_语法:**`[(x)]`**。
|
||
`[(x)]`语法结合了_属性绑定_的方括号`[x]`和_事件绑定_的圆括号`(x)`。
|
||
.callout.is-important
|
||
header [( )] = banana in a box
|
||
header [( )] = 盒子里的香蕉
|
||
:marked
|
||
Visualize a *banana in a box* to remember that the parentheses go _inside_ the brackets.
|
||
|
||
想象*盒子里的香蕉*来记住方括号套圆括号。
|
||
|
||
:marked
|
||
The `[(x)]` syntax is easy to demonstrate when the element has a settable property called `x`
|
||
and a corresponding event named `xChange`.
|
||
Here's a `SizerComponent` that fits the pattern.
|
||
It has a `size` value property and a companion `sizeChange` event:
|
||
|
||
当一个元素拥有可以设置的属性`x`和对应的事件`xChange`时,解释`[(x)]`语法就容易多了。
|
||
下面的`SizerComponent`符合这个模式。它有`size`属性和伴随的`sizeChange`事件:
|
||
|
||
+makeExample('app/sizer.component.ts')
|
||
|
||
:marked
|
||
The initial `size` is an input value from a property binding.
|
||
Clicking the buttons increases or decreases the `size`, within min/max values constraints,
|
||
and then raises (_emits_) the `sizeChange` event with the adjusted size.
|
||
|
||
`size`的初始值是一个输入值,来自属性绑定。(译注:注意`size`前面的`@Input`)
|
||
点击按钮,在最小/最大值范围限制内增加或者减少`size`。
|
||
然后用调整后的`size`触发`sizeChange`事件。
|
||
|
||
Here's an example in which the `AppComponent.fontSizePx` is two-way bound to the `SizerComponent`:
|
||
|
||
下面的例子中,`AppComponent.fontSize`被双向绑定到`SizerComponent`:
|
||
|
||
+makeExcerpt('app/app.component.html', 'two-way-1', '')
|
||
|
||
:marked
|
||
The `AppComponent.fontSizePx` establishes the initial `SizerComponent.size` value.
|
||
Clicking the buttons updates the `AppComponent.fontSizePx` via the two-way binding.
|
||
The revised `AppComponent.fontSizePx` value flows through to the _style_ binding, making the displayed text bigger or smaller.
|
||
Try it in the <live-example></live-example>.
|
||
|
||
`SizerComponent.size`初始值是`AppComponent.fontSizePx`。
|
||
点击按钮时,通过双向绑定更新`AppComponent.fontSizePx`。
|
||
被修改的`AppComponent.fontSizePx`通过_样式_绑定,改变文本的显示大小。
|
||
试一下<live-example>在线例子</live-example>。
|
||
|
||
The two-way binding syntax is really just syntactic sugar for a _property_ binding and an _event_ binding.
|
||
Angular _desugars_ the `SizerComponent` binding into this:
|
||
|
||
双向绑定语法实际上是_属性_绑定和_事件绑定_的语法糖。
|
||
Angular将`SizerComponent`的绑定分解成这样:
|
||
|
||
+makeExcerpt('app/app.component.html', 'two-way-2', '')
|
||
|
||
:marked
|
||
The `$event` variable contains the payload of the `SizerComponent.sizeChange` event.
|
||
Angular assigns the `$event` value to the `AppComponent.fontSizePx` when the user clicks the buttons.
|
||
|
||
`$event`变量包含了`SizerComponent.sizeChange`事件的荷载。
|
||
当用户点击按钮时,Angular 将`$event`赋值给`AppComponent.fontSizePx`。
|
||
|
||
Clearly the two-way binding syntax is a great convenience compared to separate property and event bindings.
|
||
|
||
很清楚,比起单独绑定属性和事件,双向数据绑定语法显得非常方便。
|
||
|
||
We'd like to use two-way binding with HTML form elements like `<input>` and `<select>`.
|
||
Sadly, no native HTML element follows the `x` value and `xChange` event pattern.
|
||
|
||
我们希望能在像`<input>`和`<select>`这样的 HTML 元素上使用双向数据绑定。
|
||
可惜,原生 HTML 元素不遵循`x`值和`xChange`事件的模式。
|
||
|
||
Fortunately, the Angular [_NgModel_](#ngModel) directive is a bridge that enables two-way binding to form elements.
|
||
|
||
幸运的是,Angular 以 [_NgModel_](#ngModel) 指令为桥梁,允许在表单元素上使用双向数据绑定。
|
||
|
||
a#ngModel
|
||
.l-main-section
|
||
:marked
|
||
## Two-way binding with NgModel
|
||
|
||
## 使用 NgModel 进行双向数据绑定
|
||
|
||
When developing data entry forms, we often want to both display a data property and update that property when the user makes changes.
|
||
|
||
当开发数据输入表单时,我们经常希望能显示数据属性,并在用户做出变更时更新该属性。
|
||
|
||
Two-way data binding with the `NgModel` directive makes that easy. Here's an example:
|
||
|
||
使用`NgModel`指令进行双向数据绑定让它变得更加容易。请看下例:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgModel-1')(format=".")
|
||
|
||
+ifDocsFor('ts|js')
|
||
.callout.is-important
|
||
header FormsModule is Required to use ngModel
|
||
|
||
header 要使用 ngModel,必须导入 FormsModule
|
||
|
||
:marked
|
||
Before we can use the `ngModel` directive in a two-way data binding,
|
||
we must import the `FormsModule` and add it to the Angular module's `imports` list.
|
||
Learn more about the `FormsModule` and `ngModel` in the
|
||
[Forms](../guide/forms.html#ngModel) chapter.
|
||
|
||
在使用`ngModel`做双向数据绑定之前,得先导入`FormsModule`,
|
||
把它加入 Angular 模块的`imports`列表。
|
||
学习关于`FormsModule`和`ngModel`的更多知识,参见[表单](../guide/forms.html#ngModel)。
|
||
|
||
:marked
|
||
Here's how to import the `FormsModule` to make `[(ngModel)]` available.
|
||
|
||
下面展示了如何导入`FormsModule`,让`[(ngModel)]`变得可用:
|
||
+makeExample('template-syntax/ts/app/app.module.1.ts', '', 'app.module.ts (FormsModule import)')
|
||
|
||
:marked
|
||
### Inside `[(ngModel)]`
|
||
|
||
### `[(ngModel)]`内幕
|
||
|
||
Looking back at the `firstName` binding, it's important to note that
|
||
we could have achieved the same result with separate bindings to
|
||
the `<input>` element's `value` property and `input` event.
|
||
|
||
回顾一下`firstName`的绑定,值得注意的是,可以通过分别绑定`<input>`元素的`value`属性和`input事件来实现同样的效果。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'without-NgModel')(format=".")
|
||
:marked
|
||
That’s cumbersome. Who can remember which element property to set and which element event emits user changes?
|
||
How do we extract the currently displayed text from the input box so we can update the data property?
|
||
Who wants to look that up each time?
|
||
|
||
这样很笨拙。谁能记住哪个元素属性用于设置,哪个用于发出用户更改?
|
||
如何从输入框中提取出当前显示的文本,以便更新数据属性?
|
||
谁想每次都去查一遍?
|
||
|
||
That `ngModel` directive hides these onerous details behind its own `ngModel` input and `ngModelChange` output properties.
|
||
|
||
`ngModel`指令通过它自己的`ngModel`输入属性和`ngModelChange`输出属性隐藏了这些繁琐的细节。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgModel-3')(format=".")
|
||
.l-sub-section
|
||
:marked
|
||
The `ngModel` data property sets the element's value property and the `ngModelChange` event property
|
||
listens for changes to the element's value.
|
||
|
||
`ngModel`数据属性设置元素的 value 属性,`ngModelChange`事件属性监听元素 value 的变化。
|
||
|
||
The details are specific to each kind of element and therefore the `NgModel` directive only works for specific form elements,
|
||
such as the input text box, that are supported by a [ControlValueAccessor](../api/forms/index/ControlValueAccessor-interface.html).
|
||
|
||
每种元素的特点各不相同,所以`NgModel`指令只能在一些特定表单元素上使用,例如输入文本框,因为它们支持 [ControlValueAccessor](../api/forms/index/ControlValueAccessor-interface.html)。
|
||
|
||
We can't apply `[(ngModel)]` to a custom component until we write a suitable *value accessor*,
|
||
a technique that is beyond the scope of this chapter.
|
||
That's something we might want to do for an Angular component or a WebComponent whose API we can't control.
|
||
|
||
除非写一个合适的*值访问器*,否则不能把`[(ngModel)]`用在自定义组件上。
|
||
但*值访问器*技术超出了本章的范围。
|
||
对于不能控制其 API 的 Angular 组件或者 Web 组件,可能需要为其添加 *value accessor*。
|
||
|
||
It's completely unnecessary for an Angular component that we _do_ control ... because we can name the value and event properties
|
||
to suit Angular's basic [two-way binding syntax](#two-way) and skip `NgModel` altogether.
|
||
|
||
但是对于我们能控制的 Angular 组件来说,这么做就完全没有必要了。
|
||
因为可以指定值和事件属性名字来进行基本的 Angular [双向绑定语法](#two-way),完全不用`NgModel`。
|
||
|
||
:marked
|
||
Separate `ngModel` bindings is an improvement over binding to the element's native properties. We can do better.
|
||
|
||
独立的`ngModel`绑定相比直接绑定元素的原生属性是个改进,但还能做得更好。
|
||
|
||
We shouldn't have to mention the data property twice. Angular should be able to capture the component’s data property and set it
|
||
with a single declaration — which it can with the `[(ngModel)]` syntax:
|
||
|
||
我们不应该提及数据属性两次。Angular 应该能捕捉组件的数据属性,并用一条声明来设置它——依靠`[(ngModel)]`,可以这么做:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgModel-1')(format=".")
|
||
:marked
|
||
Is `[(ngModel)]` all we need? Is there ever a reason to fall back to its expanded form?
|
||
|
||
`[(ngModel)]`就是我们所需的一切吗?有没有什么理由需要回退到它的展开形式?
|
||
|
||
The `[(ngModel)]` syntax can only _set_ a data-bound property.
|
||
If we need to do something more or something different, we need to write the expanded form ourselves.
|
||
|
||
`[(ngModel)]`语法只能_设置_一个数据绑定属性。
|
||
如果需要做更多或不同的事情,就得自己用它的展开形式。
|
||
|
||
Let's try something silly like forcing the input value to uppercase:
|
||
|
||
来做点淘气的事吧,比如强制让输入值变成大写形式:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgModel-4')(format=".")
|
||
:marked
|
||
Here are all variations in action, including the uppercase version:
|
||
|
||
下面是实际操作中的所有变体形式,包括这个大写版本:
|
||
figure.image-display
|
||
img(src='/resources/images/devguide/template-syntax/ng-model-anim.gif' alt="NgModel variations")
|
||
|
||
.l-main-section
|
||
:marked
|
||
<a id="directives"></a>
|
||
## Built-in directives
|
||
|
||
## 内置指令
|
||
|
||
Earlier versions of Angular included over seventy built-in directives.
|
||
The community contributed many more, and countless private directives
|
||
have been created for internal applications.
|
||
|
||
上一版本的 Angular 中包含了超过 70 个内置指令。
|
||
社区贡献了更多,这还没算为内部应用而创建的无数私有指令。
|
||
|
||
We don’t need many of those directives in Angular.
|
||
Quite often we can achieve the same results with the more capable and expressive Angular binding system.
|
||
Why create a directive to handle a click when we can write a simple binding such as this?
|
||
|
||
在新版的 Angular 中不需要那么多指令。
|
||
使用更强大、更富有表现力的 Angular 绑定系统,其实可以达到同样的效果。
|
||
如果能用简单的绑定达到目的,为什么还要创建指令来处理点击事件呢?
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'event-binding-1')(format=".")
|
||
:marked
|
||
We still benefit from directives that simplify complex tasks.
|
||
Angular still ships with built-in directives; just not as many.
|
||
We'll write our own directives, just not as many.
|
||
|
||
我们仍然可以从简化复杂任务的指令中获益。
|
||
Angular 发布时仍然带有内置指令,只是没那么多了。
|
||
我们仍会写自己的指令,只是没那么多了。
|
||
|
||
This segment reviews some of the most frequently used built-in directives.
|
||
|
||
下面来看一下那些最常用的内置指令。
|
||
|
||
<a id="ngClass"></a>
|
||
.l-main-section
|
||
:marked
|
||
### NgClass
|
||
|
||
### NgClass
|
||
|
||
We typically control how elements appear
|
||
by adding and removing CSS classes dynamically.
|
||
We can bind to `NgClass` to add or remove several classes simultaneously.
|
||
|
||
我们经常用动态添加或删除 CSS 类的方式来控制元素如何显示。
|
||
通过绑定到`NgClass`,可以同时添加或移除多个类。
|
||
|
||
A [class binding](#class-binding) is a good way to add or remove a *single* class.
|
||
|
||
[CSS 类绑定](#class-binding) 是添加或删除*单个*类的最佳途径。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'class-binding-3a')(format=".")
|
||
:marked
|
||
The `NgClass` directive may be the better choice
|
||
when we want to add or remove *many* CSS classes at the same time.
|
||
|
||
当想要同时添加或移除*多个* CSS 类时,`NgClass`指令可能是更好的选择。
|
||
|
||
A good way to apply `NgClass` is by binding it to a key:value control !{__objectAsMap}. Each key of the object is a CSS class name; its value is `true` if the class should be added, `false` if it should be removed.
|
||
|
||
绑定到一个 key:value 形式的控制对象,是应用`NgClass`的好方式。这个对象中的每个 key 都是一个 CSS 类名,如果它的 value 是`true`,这个类就会被加上,否则就会被移除。
|
||
|
||
:marked
|
||
Consider a component method such as `setClasses` that manages the state of three CSS classes:
|
||
|
||
下面的组件方法`setClasses`管理了三个 CSS 类的状态:
|
||
+makeExample('template-syntax/ts/app/app.component.ts', 'setClasses')(format=".")
|
||
:marked
|
||
Now we can add an `NgClass` property binding that calls `setClasses`
|
||
and sets the element's classes accordingly:
|
||
|
||
现在,可以添加`NgClass`属性绑定,它会调用`setClasses`,并相应地设置元素的类:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgClass-1')(format=".")
|
||
|
||
<a id="ngStyle"></a>
|
||
.l-main-section
|
||
:marked
|
||
### NgStyle
|
||
|
||
### NgStyle
|
||
|
||
We can set inline styles dynamically, based on the state of the component.
|
||
Binding to `NgStyle` lets us set many inline styles simultaneously.
|
||
|
||
我们可以根据组件的状态动态设置内联样式。
|
||
`NgStyle`绑定可以同时设置多个内联样式。
|
||
|
||
A [style binding](#style-binding) is an easy way to set a *single* style value.
|
||
|
||
[样式绑定](#style-binding)是设置*单一*样式值的简单方式。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgStyle-1')(format=".")
|
||
:marked
|
||
The `NgStyle` directive may be the better choice
|
||
when we want to set *many* inline styles at the same time.
|
||
|
||
如果要同时设置*多个*内联样式,`NgStyle`指令可能是更好的选择。
|
||
|
||
We apply `NgStyle` by binding it to a key:value control !{__objectAsMap}.
|
||
Each key of the object is a style name; its value is whatever is appropriate for that style.
|
||
|
||
`NgStyle`需要绑定到一个 key:value 控制对象。
|
||
对象的每个 key 是样式名,它的 value 是能用于这个样式的任何值。
|
||
|
||
Consider a component method such as `setStyles` that returns an object defining three styles:
|
||
|
||
下面的组件方法`setStyles`,返回一个定义了三种样式的对象:
|
||
+makeExample('template-syntax/ts/app/app.component.ts', 'setStyles')(format=".")
|
||
:marked
|
||
Now we just add an `NgStyle` property binding that calls `setStyles`
|
||
and sets the element's styles accordingly:
|
||
|
||
现在添加`NgStyle`属性绑定,让它调用`setStyles`,并相应地设置元素的样式:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgStyle-2')(format=".")
|
||
|
||
<a id="ngIf"></a>
|
||
.l-main-section
|
||
:marked
|
||
### NgIf
|
||
|
||
### NgIf
|
||
|
||
We can add an element subtree (an element and its children) to the DOM by binding an `NgIf` directive to a #{_truthy} expression.
|
||
|
||
通过绑定`NgIf`指令到真值表达式,可以把元素子树(元素及其子元素)添加到 DOM 上。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgIf-1')(format=".")
|
||
|
||
.alert.is-critical
|
||
:marked
|
||
Don't forget the asterisk (`*`) in front of `ngIf`.
|
||
For more information, see [\* and <template>](#star-template).
|
||
|
||
别忘了`ngIf`前面的星号(`*`)。
|
||
更多信息,见 [\* 与 <template>](#star-template)。
|
||
:marked
|
||
Binding to a #{_falsey} expression removes the element subtree from the DOM.
|
||
|
||
绑定到假值表达式将从 DOM 中移除元素子树。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgIf-2')(format=".")
|
||
|
||
block dart-no-truthy-falsey
|
||
//- N/A
|
||
|
||
:marked
|
||
#### Visibility and NgIf are not the same
|
||
|
||
#### 可见性和NgIf不是一回事
|
||
|
||
We can show and hide an element subtree (the element and its children) with a
|
||
[class](#class-binding) or [style](#style-binding) binding:
|
||
|
||
我们可以通过[类绑定](#class-binding)或[样式绑定](#style-binding)来显示和隐藏元素子树(元素及其子元素)。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgIf-3')(format=".")
|
||
:marked
|
||
Hiding a subtree is quite different from excluding a subtree with `NgIf`.
|
||
|
||
隐藏子树和用`NgIf`排除子树是截然不同的。
|
||
|
||
When we hide the element subtree, it remains in the DOM.
|
||
Components in the subtree are preserved, along with their state.
|
||
Angular may continue to check for changes even to invisible properties.
|
||
The subtree may tie up substantial memory and computing resources.
|
||
|
||
当隐藏子树时,它仍然留在 DOM 中。
|
||
子树中的组件及其状态仍然保留着。
|
||
即使对于不可见属性,Angular 也会继续检查变更。
|
||
子树可能占用相当可观的内存和运算资源。
|
||
|
||
When `NgIf` is `false`, Angular physically removes the element subtree from the DOM.
|
||
It destroys components in the subtree, along with their state, potentially freeing up substantial resources and
|
||
resulting in better performance for the user.
|
||
|
||
当`NgIf`为`false`时,Angular 从 DOM 中物理地移除了这个元素子树。
|
||
它销毁了子树中的组件及其状态,也潜在释放了可观的资源,最终让用户体验到更好的性能。
|
||
|
||
The show/hide technique is probably fine for small element trees.
|
||
We should be wary when hiding large trees; `NgIf` may be the safer choice. Always measure before leaping to conclusions.
|
||
|
||
显示 / 隐藏技术用在小型元素树上可能还不错。
|
||
但在隐藏大树时我们得小心;`NgIf`可能是更安全的选择。但要记住:永远得先测量,再下结论。
|
||
|
||
<a id="ngSwitch"></a>
|
||
.l-main-section
|
||
:marked
|
||
### NgSwitch
|
||
|
||
### NgSwitch
|
||
|
||
We bind to `NgSwitch` when we want to display *one* element tree (an element and its children)
|
||
from a *set* of possible element trees, based on some condition.
|
||
Angular puts only the *selected* element tree into the DOM.
|
||
|
||
当需要从*一组*可能的元素树中根据条件显示*一个*时,我们就把它绑定到`NgSwitch`。
|
||
Angular 将只把*选中的*元素树放进 DOM 中。
|
||
|
||
Here’s an example:
|
||
|
||
下面是例子:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgSwitch')(format=".")
|
||
:marked
|
||
We bind the parent `NgSwitch` directive to an expression returning a *switch value*.
|
||
The value is a string in this example, but it can be a value of any type.
|
||
|
||
我们把作为父指令的`NgSwitch`绑定到能返回*开关值*的表达式。
|
||
本例中,这个值是字符串,但它也可以是任何类型的值。
|
||
|
||
In this example, the parent `NgSwitch` directive controls a set of child `<span>` elements.
|
||
A `<span>` is either pegged to a *match value* expression or marked as the default.
|
||
|
||
这个例子中,父指令`NgSwitch`控制一组`<span>`子元素。
|
||
每个`<span>`或者挂在*匹配值*表达式上,或者被标记为默认情况。
|
||
|
||
**At any particular moment, at most one of these *spans* is in the DOM.**
|
||
|
||
**任何时候,这些 *span* 中最多只有一个会出现在 DOM 中。**
|
||
|
||
If the *span*’s *match value* equals the switch value, Angular adds the `<span>` to the DOM.
|
||
If none of the *spans* is a match, Angular adds the default *span* to the DOM.
|
||
Angular removes and destroys all other *spans*.
|
||
|
||
如果这个 *span* 的*匹配值*等于*开关值*,Angular 就把这个`<span>`添加到 DOM 中。
|
||
如果没有任何 *span* 匹配上,Angular 就把默认的 *span* 添加到 DOM 中。
|
||
Angular 会移除并销毁所有其它的 *span*。
|
||
.l-sub-section
|
||
:marked
|
||
We could substitute any element for the *span* in this example.
|
||
That element could be a `<div>` with a vast subtree of its own elements.
|
||
Only the matching `<div>` and its subtree would appear in the DOM;
|
||
the others would be removed.
|
||
|
||
可以用任何其它元素代替本例中的 *span*。
|
||
那个元素可以是带有巨大子树的`<div>`。
|
||
只有匹配的`<div>`和它的子树会显示在 DOM 中,其它的则会被移除。
|
||
:marked
|
||
Three collaborating directives are at work here:
|
||
|
||
这里有三个相互合作的指令:
|
||
1. `ngSwitch`: bound to an expression that returns the switch value
|
||
|
||
`ngSwitch`:绑定到返回开关值的表达式
|
||
|
||
1. `ngSwitchCase`: bound to an expression returning a match value
|
||
|
||
`ngSwitchCase`:绑定到返回匹配值的表达式
|
||
|
||
1. `ngSwitchDefault`: a marker attribute on the default element
|
||
|
||
`ngSwitchDefault`:用于标记出默认元素的 attribute
|
||
|
||
.alert.is-critical
|
||
:marked
|
||
**Do *not*** put the asterisk (`*`) in front of `ngSwitch`. Use the property binding instead.
|
||
|
||
**不要**在`ngSwitch`的前面加星号 (`*`),而应该用属性绑定。
|
||
|
||
**Do** put the asterisk (`*`) in front of `ngSwitchCase` and `ngSwitchDefault`.
|
||
For more information, see [\* and <template>](#star-template).
|
||
|
||
**要**把星号 (`*`) 放在`ngSwitchCase`和`ngSwitchDefault`的前面。
|
||
要了解更多信息,见[ \* 与 <template>](#star-template)。
|
||
|
||
<a id="ngFor"></a>
|
||
.l-main-section
|
||
:marked
|
||
### NgFor
|
||
|
||
### NgFor
|
||
|
||
`NgFor` is a _repeater_ directive — a way to customize data display.
|
||
|
||
`NgFor`是一个_重复器_指令 —— 自定义数据显示的一种方式。
|
||
|
||
Our goal is to present a list of items. We define a block of HTML that defines how a single item should be displayed.
|
||
We tell Angular to use that block as a template for rendering each item in the list.
|
||
|
||
我们的目标是展示一个由多个条目组成的列表。首先定义了一个 HTML 块,它规定了单个条目应该如何显示。
|
||
再告诉 Angular 把这个块当做模板,渲染列表中的每个条目。
|
||
|
||
Here is an example of `NgFor` applied to a simple `<div>`:
|
||
|
||
下例中,`NgFor`应用在一个简单的`<div>`上:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgFor-1')(format=".")
|
||
:marked
|
||
We can also apply an `NgFor` to a component element, as in this example:
|
||
|
||
也可以把`NgFor`应用在一个组件元素上,就下例这样:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgFor-2')(format=".")
|
||
|
||
.alert.is-critical
|
||
:marked
|
||
Don't forget the asterisk (`*`) in front of `ngFor`.
|
||
For more information, see [\* and <template>](#star-template).
|
||
|
||
不要忘了`ngFor`前面的星号 (`*`)。
|
||
更多信息,见[ \* 与 <template>](#star-template)
|
||
:marked
|
||
The text assigned to `*ngFor` is the instruction that guides the repeater process.
|
||
|
||
赋值给`*ngFor`的文本是用于指导重复器如何工作的指令。
|
||
|
||
<a id="ngForMicrosyntax"></a>
|
||
:marked
|
||
#### NgFor microsyntax
|
||
|
||
#### NgFor 微语法
|
||
|
||
The string assigned to `*ngFor` is not a [template expression](#template-expressions).
|
||
It’s a *microsyntax* — a little language of its own that Angular interprets. In this example, the string `"let hero of heroes"` means:
|
||
|
||
赋值给`*ngFor`的字符串不是[模板表达式](#template-expressions)。
|
||
它是一个*微语法* —— 由 Angular 自己解释的小型语言。在这个例子中,字符串`"let hero of heroes"`的含义是:
|
||
|
||
> *Take each hero in the `heroes` #{_array}, store it in the local `hero` variable, and make it available to the templated HTML for each iteration.*
|
||
|
||
> *取出`heroes`数组中的每个英雄,把它存入局部变量`hero`中,并在每次迭代时对模板 HTML 可用*
|
||
|
||
Angular translates this instruction into a new set of elements and bindings.
|
||
|
||
Angular 把这个指令翻译成一组元素和绑定。
|
||
:marked
|
||
In the two previous examples, the `ngFor` directive iterates over the `heroes` #{_array} returned by the parent component’s `heroes` property,
|
||
stamping out instances of the element to which it is applied.
|
||
Angular creates a fresh instance of the template for each hero in the array.
|
||
|
||
在前面的两个例子中,`ngFor`指令在`heroes`数组上进行迭代(它是由父组件的`heroes`属性返回的),
|
||
以其所在的元素为模板“冲压”出很多实例。
|
||
Angular 为数组中的每个英雄创建了此模板的一个全新实例。
|
||
|
||
The `let` keyword before `hero` creates a template input variable called `hero`.
|
||
|
||
`hero`前面的`let`关键字创建了名叫`hero`的模板输入变量。
|
||
|
||
.alert.is-critical
|
||
:marked
|
||
A template input variable is **not** the same as a [template reference variable](#ref-vars)!
|
||
|
||
模板输入变量和[模板引用变量](#ref-vars)**不是**一回事!
|
||
|
||
:marked
|
||
We use this variable within the template to access a hero’s properties,
|
||
as we’re doing in the interpolation.
|
||
We can also pass the variable in a binding to a component element,
|
||
as we're doing with `hero-detail`.
|
||
|
||
在模板中使用这个变量来访问英雄的属性,就像在插值表达式中所做的那样。
|
||
也可以把这个变量传给组件元素上的绑定,就像对`hero-detail`所做的那样。
|
||
|
||
:marked
|
||
#### NgFor with index
|
||
|
||
#### 带索引的 NgFor
|
||
|
||
The `ngFor` directive supports an optional `index` that increases from 0 to the length of the array for each iteration.
|
||
We can capture the index in a template input variable and use it in our template.
|
||
|
||
`ngFor`指令支持可选的`index`,它在迭代过程中会从 0 增长到“数组的长度”。
|
||
可以通过模板输入变量来捕获这个 index,并在模板中使用。
|
||
|
||
The next example captures the index in a variable named `i`, using it to stamp out rows like "1 - Hercules Son of Zeus".
|
||
|
||
下例把 index 捕获到名叫`i`的变量中,使用它“冲压出”像 "1 - Hercules Son of Zeus" 这样的条目。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgFor-3')(format=".")
|
||
.l-sub-section
|
||
:marked
|
||
Learn about other special *index-like* values such as `last`, `even`, and `odd` in the [NgFor API reference](../api/common/index/NgFor-directive.html).
|
||
|
||
要学习更多的*类似 index* 的值,例如`last`、`even`和`odd`,请参阅 [NgFor API 参考](../api/common/index/NgFor-directive.html)。
|
||
|
||
:marked
|
||
#### NgForTrackBy
|
||
|
||
#### NgForTrackBy
|
||
|
||
The `ngFor` directive has the potential to perform poorly, especially with large lists.
|
||
A small change to one item, an item removed, or an item added can trigger a cascade of DOM manipulations.
|
||
|
||
`ngFor`指令有时候会性能较差,特别是在大型列表中。
|
||
对一个条目的一丁点改动、移除或添加,都会导致级联的 DOM 操作。
|
||
|
||
For example, we could refresh the list of heroes by re-querying the server.
|
||
The refreshed list probably contains most, if not all, of the previously displayed heroes.
|
||
|
||
例如,我们可以通过重新从服务器查询来刷新英雄列表。
|
||
刷新后的列表可能包含很多(如果不是全部的话)以前显示过的英雄。
|
||
|
||
*We* know this because the `id` of each hero hasn't changed.
|
||
But Angular sees only a fresh list of new object references.
|
||
It has no choice but to tear down the old list, discard those DOM elements, and re-build a new list with new DOM elements.
|
||
|
||
*我们*知道这一点,是因为每个英雄的`id`没有变化。
|
||
但在 Angular 看来,它只是一个由新的对象引用构成的新列表,
|
||
它没有选择,只能清理旧列表、舍弃那些 DOM 元素,并且用新的 DOM 元素来重建一个新列表。
|
||
|
||
Angular can avoid this churn if we give it a *tracking* function that tells it what we know:
|
||
that two objects with the same `hero.id` are the same *hero*. Here is such a function:
|
||
|
||
如果给它一个*追踪*函数,Angular 就可以避免这种折腾。
|
||
追踪函数告诉 Angular:我们知道两个具有相同`hero.id`的对象其实是同一个英雄。
|
||
下面就是这样一个函数:
|
||
+makeExample('template-syntax/ts/app/app.component.ts', 'trackByHeroes')(format=".")
|
||
:marked
|
||
Now set the `NgForTrackBy` directive to that *tracking* function.
|
||
|
||
现在,把`NgForTrackBy`指令设置为那个*追踪*函数。
|
||
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgForTrackBy-2')(format=".")
|
||
|
||
:marked
|
||
The *tracking* function doesn't eliminate all DOM changes.
|
||
Angular may have to update the DOM element if the same-hero *properties* have changed.
|
||
But if the properties haven't changed — and most of the time they will not have changed —
|
||
Angular can leave those DOM elements alone. The list UI will be smoother and more responsive.
|
||
|
||
*追踪*函数不会阻止所有 DOM 更改。
|
||
如果同一个英雄的*属性*变化了,Angular 就可能不得不更新DOM元素。
|
||
但是如果这个属性没有变化 —— 而且大多数时候它们不会变化 ——
|
||
Angular 就能留下这些 DOM 元素。列表界面就会更加平滑,提供更好的响应。
|
||
|
||
Here is an illustration of the `NgForTrackBy` effect.
|
||
|
||
这里是关于`NgForTrackBy`效果的插图。
|
||
figure.image-display
|
||
img(src='/resources/images/devguide/template-syntax/ng-for-track-by-anim.gif' alt="NgForTrackBy")
|
||
|
||
<a id="star-template"></a>
|
||
<a id="structural-directive"></a>
|
||
.l-main-section
|
||
:marked
|
||
## * and <template>
|
||
|
||
## * 与 <template>
|
||
|
||
When we reviewed the `NgFor`, `NgIf`, and `NgSwitch` built-in directives, we called out an oddity of the syntax: the asterisk (`*`) that appears before the directive names.
|
||
|
||
当审视`NgFor`、`NgIf`和`NgSwitch`这些内置指令时,我们使用了一种古怪的语法:出现在指令名称前面的星号 (`*`)。
|
||
|
||
The `*` is a bit of syntactic sugar that makes it easier to read and write directives that modify HTML layout
|
||
with the help of templates.
|
||
`NgFor`, `NgIf`, and `NgSwitch` all add and remove element subtrees that are wrapped in `<template>` tags.
|
||
|
||
`*`是一种语法糖,它让那些需要借助模板来修改 HTML 布局的指令更易于读写。
|
||
`NgFor`、`NgIf`和`NgSwitch`都会添加或移除元素子树,这些元素子树被包裹在`<template>`标签中。
|
||
|
||
We didn't see the `<template>` tags because the `*` prefix syntax allowed us to skip those tags and
|
||
focus directly on the HTML element that we are including, excluding, or repeating.
|
||
|
||
我们没有看到`<template>`标签,那是因为这种`*`前缀语法让我们忽略了这个标签,
|
||
而把注意力直接聚焦在所要包含、排除或重复的那些 HTML 元素上。
|
||
|
||
In this section we go under the hood and see how
|
||
Angular strips away the `*` and expands the HTML into the `<template>` tags for us.
|
||
|
||
这一节,将深入研究一下,看看 Angular 是怎样扒掉这个`*`,把这段 HTML 展开到`<template>`标签中的。
|
||
|
||
:marked
|
||
### Expanding `*ngIf`
|
||
|
||
### 展开`*ngIf`
|
||
|
||
We can do what Angular does ourselves and expand the `*` prefix syntax to template syntax. Here's some code with `*ngIf`:
|
||
|
||
我们可以像 Angular 一样,自己把`*`前缀语法展开成 template 语法,这里是`*ngIf`的一些代码:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'Template-1')(format=".")
|
||
:marked
|
||
The `currentHero` is referenced twice, first as the true/false condition for `NgIf` and
|
||
again as the actual hero passed into the `HeroDetailComponent`.
|
||
|
||
`currentHero`被引用了两次,第一次是作为`NgIf`的真 / 假条件,第二次把实际的 hero 值传给了`HeroDetailComponent`。
|
||
|
||
The first expansion step transports the `ngIf` (without the `*` prefix) and its contents
|
||
into an expression assigned to a `template` directive.
|
||
|
||
展开的第一步是把`ngIf`(没有`*`前缀)和它的内容传给表达式,再赋值给`template`指令。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'Template-2a')(format=".")
|
||
:marked
|
||
The next (and final) step unfolds the HTML into a `<template>` tag and `[ngIf]` [property binding](#property-binding):
|
||
|
||
下一步,也是最后一步,是把 HTML 包裹进`<template>`标签和`[ngIf]`[属性绑定](#property-binding)中:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'Template-2')(format=".")
|
||
:marked
|
||
Notice that the `[hero]="currentHero"` binding remains on the child `<hero-detail>`
|
||
element inside the template.
|
||
|
||
注意,`[hero]="currengHero"`绑定留在了模板中的子元素`<hero-detail>`上。
|
||
|
||
block remember-the-brackets
|
||
.callout.is-critical
|
||
header Remember the brackets!
|
||
header 别忘了方括号!
|
||
:marked
|
||
Don’t make the mistake of writing `ngIf="currentHero"`!
|
||
That syntax assigns the *string* value `"currentHero"` to `ngIf`.
|
||
In JavaScript a non-empty string is a truthy value, so `ngIf` would always be
|
||
`true` and Angular would always display the `hero-detail`
|
||
… even when there is no `currentHero`!
|
||
|
||
不要误写为`ngIf="currentHero"`!
|
||
这种语法会把一个字符串"currentHero"赋值给`ngIf`。
|
||
在 JavaScript 中,非空的字符串是真值,所以`ngIf`总会是`true`,而 Angular 将永远显示`hero-detail`…… 即使根本没有`currentHero`!
|
||
|
||
:marked
|
||
### Expanding `*ngSwitch`
|
||
|
||
### 展开`*ngSwitch`
|
||
|
||
A similar transformation applies to `*ngSwitch`. We can unfold the syntax ourselves.
|
||
Here's an example, first with `*ngSwitchCase` and `*ngSwitchDefault` and then again with `<template>` tags:
|
||
|
||
类似的转换也适用于`*ngSwitch`。我们可以自己解开这个语法糖。
|
||
下例中,首先是`*ngSwitchCase`和`*ngSwitchDefault`,然后再解出`<template>`标签:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'NgSwitch-expanded')(format=".")
|
||
:marked
|
||
The `*ngSwitchCase` and `*ngSwitchDefault` expand in exactly the same manner as `*ngIf`,
|
||
wrapping their former elements in `<template>` tags.
|
||
|
||
`*ngSwitchWhen`和`*ngSwitchDefault`用和`*ngIf`完全相同的方式展开,把它们以前的元素包裹在`<template>`标签中。
|
||
|
||
Now we can see why the `ngSwitch` itself is not prefixed with an asterisk (*).
|
||
It does not define content. It's job is to control a collection of templates.
|
||
|
||
现在,应该明白为什么`ngSwitch`本身不能用星号 (*) 前缀了吧?
|
||
它没有定义内容,它的工作是控制一组模板。
|
||
|
||
In this case, it governs two sets of `ngSwitchCase` and `NgSwitchDefault` directives.
|
||
We should expect it to display the values of the selected template twice,
|
||
once for the (*) prefixed version and once for the expanded template version.
|
||
That's exactly what we see in this example:
|
||
|
||
上面这种情况下,它管理两组`NgSwitchCase`和`NgSwitchDefault`指令,一次是 (*) 前缀的版本,一次是展开模板后的版本。
|
||
我们也期待它显示所选模板的值两次。这正是在这个例子中看到的:
|
||
figure.image-display
|
||
img(src='/resources/images/devguide/template-syntax/ng-switch-anim.gif' alt="NgSwitch")
|
||
:marked
|
||
### Expanding `*ngFor`
|
||
|
||
### 展开`*ngFor`
|
||
|
||
The `*ngFor` undergoes a similar transformation. We begin with an `*ngFor` example:
|
||
|
||
`*ngFor`也经历类似的转换。从一个`*ngFor`的例子开始:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'Template-3a')(format=".")
|
||
:marked
|
||
Here's the same example after transporting the `ngFor` to the `template` directive:
|
||
|
||
这里是在把`ngFor`传进`template`指令后的同一个例子:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'Template-3')(format=".")
|
||
:marked
|
||
And here it is expanded further into a `<template>` tag wrapping the original `<hero-detail>` element:
|
||
|
||
下面,它被进一步扩展成了包裹着原始`<hero-detail>`元素的`<template>`标签:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'Template-4')(format=".")
|
||
:marked
|
||
The `NgFor` code is a bit more complex than `NgIf` because a repeater has more moving parts to configure.
|
||
In this case, we have to remember to create and assign the `NgForOf` directive that identifies the list and the `NgForTrackBy` directive.
|
||
Using the `*ngFor` syntax is much easier than writing out this expanded HTML ourselves.
|
||
|
||
`NgFor`的代码相对`NgIf`更复杂一点,因为重复器有更多活动部分需要配置。
|
||
这种情况下,我们就得记住添加`NgForOf`指令和`NgForTrackBy`指令,并对它们赋值。
|
||
使用`*ngFor`语法比直接写这些展开后的 HTML 本身要简单多了。
|
||
|
||
<a id="ref-vars"></a>
|
||
.l-main-section
|
||
:marked
|
||
## Template reference variables
|
||
|
||
## 模板引用变量
|
||
|
||
A **template reference variable** is a reference to a DOM element or directive within a template.
|
||
|
||
**模板引用变量**是模板中对 DOM 元素或指令的引用。
|
||
|
||
It can be used with native DOM elements but also with Angular components — in fact, it will work with any custom web component.
|
||
|
||
它能在原生 DOM 元素中使用,也能用于 Angular 组件 —— 实际上,它可以和任何自定义 Web 组件协同工作。
|
||
|
||
:marked
|
||
### Referencing a template reference variable
|
||
|
||
### 引用模板引用变量
|
||
|
||
We can refer to a template reference variable _anywhere_ in the current template.
|
||
|
||
可以在同一元素、兄弟元素或任何子元素中引用模板引用变量。
|
||
|
||
.l-sub-section
|
||
:marked
|
||
Do not define the same variable name more than once in the same template.
|
||
The runtime value will be unpredictable.
|
||
|
||
不要在同一个模版中多次定义相同变量名,否则运行时的值将会不可预测。
|
||
|
||
:marked
|
||
Here are two other examples of creating and consuming a Template reference variable:
|
||
|
||
这里是关于创建和使用模板引用变量的另外两个例子:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'ref-phone')(format=".")
|
||
:marked
|
||
The hash (`#`) prefix to "phone" means that we're defining a `phone` variable.
|
||
|
||
"phone" 的井号 (`#`) 前缀表示定义了一个`phone`变量。
|
||
.l-sub-section
|
||
:marked
|
||
Folks who don't like using the `#` character can use its canonical alternative,
|
||
the `ref-` prefix. For example, we can declare the our `phone` variable using
|
||
either `#phone` or `ref-phone`.
|
||
|
||
有些人不喜欢使用`#`字符,而是使用它的规范形式:`ref-`前缀。
|
||
例如,既能用`#phone`,也能用`ref-phone`来定义`phone`变量。
|
||
|
||
:marked
|
||
### How a variable gets its value
|
||
|
||
### 如何获取变量的值
|
||
|
||
Angular sets the variable's value to the element on which it was defined.
|
||
We defined these variables on the `input` elements.
|
||
We’re passing those `input` element objects across to the
|
||
button elements, where they're used in arguments to the `call` methods in the event bindings.
|
||
|
||
Angular 把这种变量的值设置为它所在的那个元素。
|
||
在这个`input`元素上定义了这些变量。
|
||
把那些`input`元素对象传给 button 元素,在事件绑定中,它们作为参数传给了`call`方法。
|
||
|
||
:marked
|
||
### NgForm and template reference variables
|
||
|
||
### NgForm 和模板引用变量
|
||
|
||
Let's look at one final example: a form, the poster child for template reference variables.
|
||
|
||
让我们看看最后一个例子:表单,使用模板引用变量的典范。
|
||
|
||
The HTML for a form can be quite involved, as we saw in the [Forms](forms.html) chapter.
|
||
The following is a *simplified* example — and it's not simple at all.
|
||
|
||
正如在[表单](forms.html)一章中所见过的,表单的 HTML 可以做得相当复杂。
|
||
下面是*简化过的*范例 —— 虽然仍算不上多简单。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'ref-form')(format=".")
|
||
:marked
|
||
A template reference variable, `theForm`, appears three times in this example, separated
|
||
by a large amount of HTML.
|
||
|
||
模板引用变量`theForm`在这个例子中出现了三次,中间隔着一大段 HTML。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'ref-form-a')(format=".")
|
||
:marked
|
||
What is the value of `theForm`?
|
||
|
||
`theForm`变量的值是什么?
|
||
|
||
It would be the [HTMLFormElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)
|
||
if Angular hadn't taken it over.
|
||
It's actually `ngForm`, a reference to the Angular built-in `NgForm` directive that wraps the native `HTMLFormElement`
|
||
and endows it with additional superpowers such as the ability to
|
||
track the validity of user input.
|
||
|
||
如果 Angular 没有接管它,那它可能是个[HTMLFormElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)。
|
||
实际上它是个`ngForm`,对 Angular 内置指令`NgForm`的引用。
|
||
它包装了原生的`HTMLFormElement`并赋予它更多超能力,比如跟踪用户输入的有效性。
|
||
|
||
This explains how we can disable the submit button by checking `theForm.form.valid`
|
||
and pass an object with rich information to the parent component's `onSubmit` method.
|
||
|
||
这解释了该如何通过检查`theForm.form.valid`来禁用提交按钮,以及如何把一个信息量略大的对象传给父组件的`onSubmit`方法。(译注:`onSubmit`方法可能会出发事件,被父组件监听,参见下面的`输入和输出属性`和[父组件监听子组件的事件](docs/ts/latest/cookbook/component-communication.html#!#child-to-parent)。)
|
||
|
||
<a id="inputs-outputs"></a>
|
||
.l-main-section
|
||
:marked
|
||
## Input and output properties
|
||
|
||
## 输入与输出属性
|
||
|
||
So far, we’ve focused mainly on binding to component members within template expressions and statements
|
||
that appear on the *right side of the binding declaration*.
|
||
A member in that position is a data binding **source**.
|
||
|
||
迄今为止,我们主要聚焦在*绑定声明的右侧*,学习如何在模板表达式和模板语句中绑定到组件成员。
|
||
当成员出现在这个位置上,则称之为数据绑定的**源**。
|
||
|
||
This section concentrates on binding to **targets**, which are directive
|
||
properties on the *left side of the binding declaration*.
|
||
These directive properties must be declared as **inputs** or **outputs**.
|
||
|
||
本节则专注于绑定到的**目标**,它位于*绑定声明中的左侧*。
|
||
这些指令的属性必须被声明成**输入**或**输出**。
|
||
|
||
.alert.is-important
|
||
:marked
|
||
Remember: All **components** are **directives**.
|
||
|
||
记住:所有**组件**皆为**指令**。
|
||
:marked
|
||
.l-sub-section
|
||
:marked
|
||
We're drawing a sharp distinction between a data binding **target** and a data binding **source**.
|
||
|
||
我们要重点突出下绑定**目标**和绑定**源**的区别。
|
||
|
||
The *target* of a binding is to the *left* of the `=`.
|
||
The *source* is on the *right* of the `=`.
|
||
|
||
绑定的*目标*是在`=`*左侧*的部分,
|
||
*源*则是在`=`*右侧*的部分。
|
||
|
||
The *target* of a binding is the property or event inside the binding punctuation: `[]`, `()` or `[()]`.
|
||
The *source* is either inside quotes (`" "`) or within an interpolation (`{{}}`).
|
||
|
||
绑定的*目标*是绑定符:`[]`、`()`或`[()]`中的属性或事件名,
|
||
*源*则是引号 (`" "`) 中的部分或插值符号 (`{{}}`) 中的部分。
|
||
|
||
Every member of a **source** directive is automatically available for binding.
|
||
We don't have to do anything special to access a directive member in a template expression or statement.
|
||
|
||
**源**指令中的每个成员都会自动在绑定中可用。
|
||
不需要特别做什么,就能在模板表达式或语句中访问指令的成员。
|
||
|
||
We have *limited* access to members of a **target** directive.
|
||
We can only bind to properties that are explicitly identified as *inputs* and *outputs*.
|
||
|
||
访问**目标**指令中的成员则*受到限制*。
|
||
只能绑定到那些显式标记为*输入*或*输出*的属性。
|
||
:marked
|
||
In the following example, `iconUrl` and `onSave` are members of a component
|
||
that are referenced within quoted syntax to the right of the `=`.
|
||
|
||
在下面的例子中,`iconUrl`和`onSave`是组件的成员,它们在`=`右侧引号语法中被引用了。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'io-1')(format=".")
|
||
:marked
|
||
They are *neither inputs nor outputs* of the component. They are data sources for their bindings.
|
||
|
||
它们既不是组件的*输入*也不是*输出*。它们是绑定的数据源。
|
||
|
||
Now look at `HeroDetailComponent` when it is the **target of a binding**.
|
||
|
||
现在,看看`HeroDetailComponent`,它是**绑定的目标**。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'io-2')(format=".")
|
||
:marked
|
||
Both `HeroDetailComponent.hero` and `HeroDetailComponent.deleteRequest` are on the **left side** of binding declarations.
|
||
`HeroDetailComponent.hero` is inside brackets; it is the target of a property binding.
|
||
`HeroDetailComponent.deleteRequest` is inside parentheses; it is the target of an event binding.
|
||
|
||
`HeroDetailComponent.hero`和`HeroDetailComponent.deleteRequest`都在绑定声明的**左侧**。
|
||
`HeroDetailComponent.hero`在方括号中,它是属性绑定的目标。
|
||
`HeroDetailComponent.deleteRequest`在圆括号中,它是事件绑定的目标。
|
||
|
||
### Declaring input and output properties
|
||
|
||
### 声明输入和输出属性
|
||
|
||
Target properties must be explicitly marked as inputs or outputs.
|
||
|
||
目标属性必须被显式的标记为输入或输出。
|
||
|
||
When we peek inside `HeroDetailComponent`, we see that these properties are marked
|
||
with decorators as input and output properties.
|
||
|
||
当我们深入`HeroDetailComponent`内部时,就会看到这些属性被装饰器标记成了输入和输出属性。
|
||
+makeExample('template-syntax/ts/app/hero-detail.component.ts', 'input-output-1')(format=".")
|
||
|
||
:marked
|
||
.l-sub-section
|
||
:marked
|
||
Alternatively, we can identify members in the `inputs` and `outputs` #{_array}s
|
||
of the directive metadata, as in this example:
|
||
|
||
另外,还可以在指令元数据的`inputs`或`outputs`数组中标记出这些成员。比如这个例子:
|
||
+makeExample('template-syntax/ts/app/hero-detail.component.ts', 'input-output-2')(format=".")
|
||
<br>
|
||
:marked
|
||
We can specify an input/output property either with a decorator or in a metadata #{_array}.
|
||
Don't do both!
|
||
|
||
既可以通过装饰器,也可以通过元数据数组来指定输入/输出属性。但别同时用!
|
||
:marked
|
||
### Input or output?
|
||
|
||
### 输入还是输出?
|
||
|
||
*Input* properties usually receive data values.
|
||
*Output* properties expose event producers, such as `EventEmitter` objects.
|
||
|
||
*输入*属性通常接收数据值。
|
||
*输出*属性暴露事件生产者,如`EventEmitter`对象。
|
||
|
||
The terms _input_ and _output_ reflect the perspective of the target directive.
|
||
|
||
_输入_和_输出_这两个词是从目标指令的角度来说的。
|
||
figure.image-display
|
||
img(src='/resources/images/devguide/template-syntax/input-output.png' alt="Inputs and outputs")
|
||
:marked
|
||
`HeroDetailComponent.hero` is an **input** property from the perspective of `HeroDetailComponent`
|
||
because data flows *into* that property from a template binding expression.
|
||
|
||
从`HeroDetailComponent`角度来看,`HeroDetailComponent.hero`是个**输入**属性,
|
||
因为数据流从模板绑定表达式流*入*那个属性。
|
||
|
||
`HeroDetailComponent.deleteRequest` is an **output** property from the perspective of `HeroDetailComponent`
|
||
because events stream *out* of that property and toward the handler in a template binding statement.
|
||
|
||
从`HeroDetailComponent`角度来看,`HeroDetailComponent.deleteRequest`是个**输出**属性,
|
||
因为事件从那个属性流*出*,流向模板绑定语句中的处理器。
|
||
|
||
h3#aliasing-io Aliasing input/output properties
|
||
|
||
h3#aliasing-io 给输入/输出属性起别名
|
||
|
||
:marked
|
||
Sometimes we want the public name of an input/output property to be different from the internal name.
|
||
|
||
有时需要让输入/输出属性的公开名字不同于内部名字。
|
||
|
||
This is frequently the case with [attribute directives](attribute-directives.html).
|
||
Directive consumers expect to bind to the name of the directive.
|
||
For example, when we apply a directive with a `myClick` selector to a `<div>` tag,
|
||
we expect to bind to an event property that is also called `myClick`.
|
||
|
||
这是使用 [attribute 指令](attribute-directives.html)时的常见情况。
|
||
指令的使用者期望绑定到指令名。例如,在`<div>`上用`myClick`选择器应用指令时,
|
||
希望绑定的事件属性也叫`myClick`。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'myClick')(format=".")
|
||
:marked
|
||
However, the directive name is often a poor choice for the name of a property within the directive class.
|
||
The directive name rarely describes what the property does.
|
||
The `myClick` directive name is not a good name for a property that emits click messages.
|
||
|
||
然而,在指令类中,直接用指令名作为自己的属性名通常都不是好的选择。
|
||
指令名很少能描述这个属性是干嘛的。
|
||
`myClick`这个指令名对于用来发出 click 消息的属性就算不上一个好名字。
|
||
|
||
Fortunately, we can have a public name for the property that meets conventional expectations,
|
||
while using a different name internally.
|
||
In the example immediately above, we are actually binding *through the* `myClick` *alias* to
|
||
the directive's own `clicks` property.
|
||
|
||
幸运的是,可以使用约定俗成的公开名字,同时在内部使用不同的名字。
|
||
在上面例子中,实际上是把`myClick`这个别名指向了指令自己的`clicks`属性。
|
||
|
||
We can specify the alias for the property name by passing it into the input/output decorator like this:
|
||
|
||
把别名传进@Input/@Output装饰器,就可以为属性指定别名,就像这样:
|
||
|
||
+makeExample('template-syntax/ts/app/click.directive.ts', 'output-myClick')(format=".")
|
||
|
||
.l-sub-section
|
||
:marked
|
||
We can also alias property names in the `inputs` and `outputs` #{_array}s.
|
||
We write a colon-delimited (`:`) string with
|
||
the directive property name on the *left* and the public alias on the *right*:
|
||
|
||
也可在`inputs`和`outputs`数组中为属性指定别名。
|
||
可以写一个冒号 (`:`) 分隔的字符串,*左侧*是指令中的属性名,*右侧*则是公开的别名。
|
||
+makeExample('template-syntax/ts/app/click.directive.ts', 'output-myClick2')(format=".")
|
||
|
||
<a id="expression-operators"></a>
|
||
.l-main-section
|
||
:marked
|
||
## Template expression operators
|
||
|
||
## 模板表达式操作符
|
||
|
||
The template expression language employs a subset of #{_JavaScript} syntax supplemented with a few special operators
|
||
for specific scenarios. We'll cover two of these operators: _pipe_ and _safe navigation operator_.
|
||
|
||
模板表达式语言使用了 JavaScript 语法的子集,并补充了几个用于特定场景的特殊操作符。
|
||
下面介绍其中的两个:_管道_和_安全导航操作符_。
|
||
|
||
:marked
|
||
<a id="pipe"></a>
|
||
### The pipe operator ( | )
|
||
|
||
### 管道操作符 ( | )
|
||
|
||
The result of an expression might require some transformation before we’re ready to use it in a binding. For example, we might want to display a number as a currency, force text to uppercase, or filter a list and sort it.
|
||
|
||
在绑定之前,表达式的结果可能需要一些转换。例如,可能希望把数字显示成金额、强制文本变成大写,或者过滤列表以及进行排序。
|
||
|
||
Angular [pipes](./pipes.html) are a good choice for small transformations such as these.
|
||
Pipes are simple functions that accept an input value and return a transformed value.
|
||
They're easy to apply within template expressions, using the **pipe operator (`|`)**:
|
||
|
||
Angular [管道](./pipes.html)对像这样的小型转换来说是个明智的选择。
|
||
管道是一个简单的函数,它接受一个输入值,并返回转换结果。
|
||
它们很容易用于模板表达式中,只要使用**管道操作符 (`|`) **就行了。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'pipes-1')(format=".")
|
||
:marked
|
||
The pipe operator passes the result of an expression on the left to a pipe function on the right.
|
||
|
||
管道操作符会把它左侧的表达式结果传给它右侧的管道函数。
|
||
|
||
We can chain expressions through multiple pipes:
|
||
|
||
还可以通过多个管道串联表达式:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'pipes-2')(format=".")
|
||
:marked
|
||
And we can also [apply parameters](./pipes.html#parameterizing-a-pipe) to a pipe:
|
||
|
||
还能对它们使用参数:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'pipes-3')(format=".")
|
||
|
||
block json-pipe
|
||
:marked
|
||
The `json` pipe is particularly helpful for debugging our bindings:
|
||
|
||
`json`管道对调试绑定特别有用:
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'pipes-json')(format=".")
|
||
:marked
|
||
The generated output would look something like this
|
||
|
||
它生成的输出是类似于这样的:
|
||
code-example(language="json").
|
||
{ "firstName": "Hercules", "lastName": "Son of Zeus",
|
||
"birthdate": "1970-02-25T08:00:00.000Z",
|
||
"url": "http://www.imdb.com/title/tt0065832/",
|
||
"rate": 325, "id": 1 }
|
||
|
||
:marked
|
||
<a id="safe-navigation-operator"></a>
|
||
### The safe navigation operator ( ?. ) and null property paths
|
||
|
||
### 安全导航操作符 ( ?. ) 和空属性路径
|
||
|
||
The Angular **safe navigation operator (`?.`)** is a fluent and convenient way to guard against null and undefined values in property paths.
|
||
Here it is, protecting against a view render failure if the `currentHero` is null.
|
||
|
||
Angular 的**安全导航操作符 (`?.`) **是一种流畅而便利的方式,用来保护出现在属性路径中 null 和 undefined 值。
|
||
下例中,当`currentHero`为空时,保护视图渲染器,让它免于失败。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'safe-2')(format=".")
|
||
|
||
block dart-safe-nav-op
|
||
//- N/A
|
||
|
||
:marked
|
||
Let’s elaborate on the problem and this particular solution.
|
||
|
||
我们来详细阐述一下这个问题和解决方案:
|
||
|
||
What happens when the following data bound `title` property is null?
|
||
|
||
如果下列数据绑定中`title`属性为空,会发生什么?
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'safe-1')(format=".")
|
||
:marked
|
||
The view still renders but the displayed value is blank; we see only "The title is" with nothing after it.
|
||
That is reasonable behavior. At least the app doesn't crash.
|
||
|
||
这个视图仍然被渲染出来,但是显示的值是空;只能看到 “The title is”,它后面却没有任何东西。
|
||
这是合理的行为。至少应用没有崩溃。
|
||
|
||
Suppose the template expression involves a property path, as in this next example
|
||
where we’re displaying the `firstName` of a null hero.
|
||
|
||
假设模板表达式涉及属性路径,在下例中,显示一个空 (null) 英雄的`firstName`。
|
||
|
||
code-example(language="html").
|
||
The null hero's name is {{nullHero.firstName}}
|
||
|
||
block null-deref-example
|
||
:marked
|
||
JavaScript throws a null reference error, and so does Angular:
|
||
|
||
JavaScript 抛出了空引用错误,Angular 也是如此:
|
||
code-example(format="nocode").
|
||
TypeError: Cannot read property 'firstName' of null in [null].
|
||
|
||
:marked
|
||
Worse, the *entire view disappears*.
|
||
|
||
晕,*整个视图都不见了*。
|
||
|
||
We could claim that this is reasonable behavior if we believed that the `hero` property must never be null.
|
||
If it must never be null and yet it is null,
|
||
we've made a programming error that should be caught and fixed.
|
||
Throwing an exception is the right thing to do.
|
||
|
||
如果确信`hero`属性永远不可能为空,可以声称这是合理的行为。
|
||
如果它必须不能为空,但它仍然是空值,实际上是制造了一个编程错误,它应该被捕获和修复。
|
||
这种情况应该抛出异常。
|
||
|
||
On the other hand, null values in the property path may be OK from time to time,
|
||
especially when we know the data will arrive eventually.
|
||
|
||
另一方面,属性路径中的空值可能会时常发生,特别是当我们知道数据最终会出现。
|
||
|
||
While we wait for data, the view should render without complaint, and
|
||
the null property path should display as blank just as the `title` property does.
|
||
|
||
当等待数据的时候,视图渲染器不应该抱怨,而应该把这个空属性路径显示为空白,就像上面`title`属性那样。
|
||
|
||
Unfortunately, our app crashes when the `currentHero` is null.
|
||
|
||
不幸的是,当`currentHero`为空的时候,应用崩溃了。
|
||
|
||
We could code around that problem with [NgIf](#ngIf).
|
||
|
||
可以通过写[NgIf](#ngIf)代码来解决这个问题。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'safe-4')(format=".")
|
||
|
||
block safe-op-alt
|
||
:marked
|
||
Or we could try to chain parts of the property path with `&&`, knowing that the expression bails out
|
||
when it encounters the first null.
|
||
|
||
或者可以尝试通过`&&`来把属性路径的各部分串起来,让它在遇到第一个空值的时候,就返回空。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'safe-5')(format=".")
|
||
|
||
:marked
|
||
These approaches have merit but can be cumbersome, especially if the property path is long.
|
||
Imagine guarding against a null somewhere in a long property path such as `a.b.c.d`.
|
||
|
||
这些方法都有价值,但是会显得笨重,特别是当这个属性路径非常长的时候。
|
||
想象一下在一个很长的属性路径(如`a.b.c.d`)中对空值提供保护。
|
||
|
||
:marked
|
||
The Angular safe navigation operator (`?.`) is a more fluent and convenient way to guard against nulls in property paths.
|
||
The expression bails out when it hits the first null value.
|
||
The display is blank, but the app keeps rolling without errors.
|
||
|
||
Angular 安全导航操作符 (`?.`) 是在属性路径中保护空值的更加流畅、便利的方式。
|
||
表达式会在它遇到第一个空值的时候跳出。
|
||
显示是空的,但应用正常工作,而没有发生错误。
|
||
+makeExample('template-syntax/ts/app/app.component.html', 'safe-6')(format=".")
|
||
:marked
|
||
It works perfectly with long property paths such as `a?.b?.c?.d`.
|
||
|
||
在像`a?.b?.c?.d`这样的长属性路径中,它工作得很完美。
|
||
|
||
.l-main-section
|
||
:marked
|
||
## Summary
|
||
|
||
## 小结
|
||
|
||
We’ve completed our survey of template syntax. Now it's time to put that knowledge to work as we write our own components and directives.
|
||
|
||
我们完成了模板语法的概述。现在,该把如何写组件和指令的知识投入到实际工作当中了。
|