填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

繫結語法:概述

Binding syntax

資料繫結會根據應用程式的狀態自動使你的頁面保持最新狀態。你可以使用資料繫結來指定諸如影象源、按鈕狀態或特定使用者的資料之類別的內容。

Data binding automatically keeps your page up-to-date based on your application's state. You use data binding to specify things such as the source of an image, the state of a button, or data for a particular user.

包含本指南中的程式碼段的工作示例,請參閱現場演練 / 下載範例

See the現場演練 / 下載範例for a working example containing the code snippets in this guide.

資料繫結和 HTML

Data binding and HTML

開發人員可以使用字串值指定屬性來訂製 HTML。在以下示例中,classsrcdisabled 修飾了 <div><img><button> 元素。

Developers can customize HTML by specifying attributes with string values. In the following example, class, src, and disabled modify the <div>, <img>, and <button> elements respectively.

      
      <div class="special">Plain old HTML</div>
<img src="images/item.png">
<button disabled>Save</button>
    

可以使用資料繫結來控制按鈕狀態等:

Use data binding to control things like the state of a button:

src/app/app.component.html
      
      <!-- Bind button disabled state to `isUnchanged` property -->
<button [disabled]="isUnchanged">Save</button>
    

請注意,繫結是繫結到 disabled 這個 Property(屬性),而不是 Attribute(屬性)。資料繫結使用的是 DOM 元素、元件和指令的 Property,而不是 HTML Attribute。

Notice that the binding is to the disabled property of the button's DOM element, not the attribute. Data binding works with properties of DOM elements, components, and directives, not HTML attributes.

HTML Attribute 和 DOM Property

HTML attributes and DOM properties

對於 Angular 繫結來說,HTML Attribute 和 DOM Property 是有顯著區別的。

Angular binding distinguishes between HTML attributes and DOM properties.

Attribute 會初始化 DOM Property,你可以配置它們以修改元素的行為。Property 則是 DOM 節點的特性。

Attributes initialize DOM properties and you can configure them to modify an element's behavior. Properties are features of DOM nodes.

  • 少數 HTML Attribute 可以 1:1 對映到同名的 Property。例如 id

    A few HTML attributes have 1:1 mapping to properties; for example, id.

  • 某些 HTML Attribute 沒有相應的 Property。例如,aria-*

    Some HTML attributes don't have corresponding properties; for example, aria-*.

  • 某些 DOM Property 沒有相應的 Attribute。例如,textContent

    Some DOM properties don't have corresponding attributes; for example, textContent.

請記住,即使 HTML Attribute 和 DOM Property 具有相同的名稱,它們也仍然是不同的。

Remember that HTML attributes and DOM properties are different things, even when they have the same name.

在 Angular 中,HTML Attribute 的唯一作用是初始化元素和指令的狀態。

In Angular, the only role of HTML attributes is to initialize element and directive state.

編寫資料繫結時,你只是在處理 DOM Property 和目標物件的事件。

When you write a data binding, you're dealing exclusively with the DOM properties and events of the target object.

範例 1:<input>

Example 1: an <input>

當瀏覽器渲染 <input type="text" value="Sarah"> 時,它將建立一個具有 value 這個 Property 的相應 DOM 節點,並將其 value 初始化為 “Sarah”。

When the browser renders <input type="text" value="Sarah">, it creates a corresponding DOM node with a value property and initializes that value to "Sarah".

      
      <input type="text" value="Sarah">
    

當用戶將 Sally 輸入到 <input> 時,DOM 元素的 value Property 會變為 Sally。但是,如果使用 input.getAttribute('value') 讀取 value,你會看到該 Attribute 保持不變 - 它仍然會返回 “Sarah”。

When the user enters Sally into the <input>, the DOM element value property becomes Sally. However, if you look at the HTML attribute value using input.getAttribute('value'), you can see that the attribute remains unchanged—it returns "Sarah".

作為 HTML Attribute 的 value 會指定初始值; 而 DOM 的 Property value 則是當前值。

The HTML attribute value specifies the initial value; the DOM value property is the current value.

要在執行的應用程式中檢視 Attribute 與 DOM Property,請參閱現場演練 / 下載範例,請特別關注繫結語法的資訊。

To see attributes versus DOM properties in a functioning app, see the現場演練 / 下載範例especially for binding syntax.

範例 2:禁用按鈕

Example 2: a disabled button

預設情況下,按鈕的 disabled Property 為 false,因此啟用了此按鈕。

A button's disabled property is false by default so the button is enabled.

當新增 disabled Attribute 時,你正在將按鈕的 disabled Property 初始化為 true,這將禁用該按鈕。

When you add the disabled attribute, you are initializing the button's disabled property to true which disables the button.

      
      <button disabled>Test Button</button>
    

新增或刪除 disabled 這個 Attribute 將禁用或啟用該按鈕。但是,該 Attribute 的值無關緊要,這就是為什麼你無法透過編寫 <button disabled="false">Still Disabled</button> 來啟用按鈕的原因。

Adding and removing the disabled attribute disables and enables the button. However, the value of the attribute is irrelevant, which is why you cannot enable a button by writing <button disabled="false">Still Disabled</button>.

要控制按鈕的狀態,請設定 disabled 這個 Property。

To control the state of the button, set the disabled property instead.

Property 和 Attribute 的比較

Property and attribute comparison

儘管從技術角度上說,可以設定 [attr.disabled] Attribute 這個繫結,但是它的值是不同的,差異在於其 Property 繫結必須是布林值,而其相應的 Attribute 繫結則取決於該值是否為 null。考慮以下情況:

Though you could technically set the [attr.disabled] attribute binding, the values are different in that the property binding must be a boolean value, while its corresponding attribute binding relies on whether the value is null or not. Consider the following:

      
      <input [disabled]="condition ? true : false">
<input [attr.disabled]="condition ? 'disabled' : null">
    

第一行使用 disabled 這個 Property,要使用布林值。第二行使用 disabled 這個 Attribute,要判定是否為 null

The first line, which uses the disabled property, uses a boolean value. The second line, which uses the disabled attribute checks for null.

通常,要使用 Property 繫結而不是 Attribute 繫結。因為布林值很容易閱讀,語法較短,並且 Property 繫結的效能更高。

Generally, use property binding over attribute binding as a boolean value is easy to read, the syntax is shorter, and a property is more performant.

要在執行的應用程式中檢視 disabled 按鈕,請參見現場演練 / 下載範例。本示例說明如何從元件中切換 disabled 這個 Property。

To see the disabled button example in a functioning application, see the現場演練 / 下載範例. This example shows you how to toggle the disabled property from the component.

資料繫結的型別

Types of data binding

Angular 根據資料流的方向提供三種類型的資料繫結:

Angular provides three categories of data binding according to the direction of data flow:

  • 從源到檢視

    From the source to view

  • 從檢視到源

    From view to source

  • 雙向,從檢視到源再到檢視

    In a two way sequence of view to source to view

繫結型別

Type

語法

Syntax

分類

Category

插值
屬性
Attribute
CSS 類別
樣式

Interpolation
Property
Attribute
Class
Style

      
      {{expression}}
[target]="expression"
bind-target="expression"
    

單向
從資料來源
到檢視

One-way
from data source
to view target

事件

Event

      
      (target)="statement"
on-target="statement"
    

從檢視到資料來源的單向繫結

One-way
from view target
to data source

雙向

Two-way

      
      [(target)]="expression"
bindon-target="expression"
    

雙向

Two-way

除插值以外的繫結型別,在等號的左側會有一個目標名稱。繫結目標是一個 Property 或事件名稱,被方括號 []、圓括號 () 或兩者共同 [()] 包裹起來。

Binding types other than interpolation have a target name to the left of the equal sign. The target of a binding is a property or event, which you surround with square brackets, [], parentheses, (), or both, [()].

[]()[()] 這些繫結標點以及字首,用來指定資料流的方向。

The binding punctuation of [], (), [()], and the prefix specify the direction of data flow.

  • 使用 [] 從源繫結到檢視。

    Use [] to bind from source to view.

  • 使用 () 從檢視繫結到源。

    Use () to bind from view to source.

  • 使用 [()] 進行雙向繫結,將檢視繫結到源再繫結到檢視。

    Use [()] to bind in a two way sequence of view to source to view.

將表示式或語句放在雙引號 "" 中等號的右側。有關更多資訊,請參見插值範本語句

Place the expression or statement to the right of the equal sign within double quotes, "". For more information see Interpolation and Template statements.

繫結型別和目標

Binding types and targets

資料繫結的目標可以是 Property、事件或 Attribute 的名稱。源指令的每個 public 成員都可以自動用於繫結範本表示式或範本語句中。下表總結了不同繫結型別的目標。

The target of a data binding can be a property, an event, or an attribute name. Every public member of a source directive is automatically available for binding in a template expression or statement. The following table summarizes the targets for the different binding types.

型別

Type

目標

Target

範例

Examples

屬性

Property

元素屬性
元件屬性
指令屬性

Element property
Component property
Directive property

srcherongClass,程式碼如下:

      
      <img [src]="heroImageUrl">
<app-hero-detail [hero]="currentHero"></app-hero-detail>
<div [ngClass]="{'special': isSpecial}"></div>
    

src, hero, and ngClass in the following:

      
      <img [src]="heroImageUrl">
<app-hero-detail [hero]="currentHero"></app-hero-detail>
<div [ngClass]="{'special': isSpecial}"></div>
    

事件

Event

元素事件
元件事件
指令事件

Element event
Component event
Directive event

clickdeleteRequestmyClick,程式碼如下:

      
      <button (click)="onSave()">Save</button>
<app-hero-detail (deleteRequest)="deleteHero()"></app-hero-detail>
<div (myClick)="clicked=$event" clickable>click me</div>
    

click, deleteRequest, and myClick in the following:

      
      <button (click)="onSave()">Save</button>
<app-hero-detail (deleteRequest)="deleteHero()"></app-hero-detail>
<div (myClick)="clicked=$event" clickable>click me</div>
    

雙向

Two-way

事件與屬性

Event and property

      
      <input [(ngModel)]="name">
    
Attribute

Attribute (少數特例情況)

Attribute (the exception)

      
      <button [attr.aria-label]="help">help</button>
    

類別

Class

class 屬性

class property

      
      <div [class.special]="isSpecial">Special</div>
    

樣式

Style

style 屬性

style property

      
      <button [style.color]="isSpecial ? 'red' : 'green'">