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

屬性繫結

Property binding

Angular 中的屬性繫結可幫助你設定 HTML 元素或指令的屬性值。使用屬性繫結,你可以執行諸如切換按鈕、以程式設計方式設定路徑,以及在元件之間共享值之類別的功能。

Property binding in Angular helps you set values for properties of HTML elements or directives. With property binding, you can do things such as toggle button functionality, set paths programmatically, and share values between components.

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

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

先決條件

Prerequisites

為了充分理解屬性繫結,你應該熟悉以下內容:

To get the most out of property binding, you should be familiar with the following:


理解資料流

Understanding the flow of data

屬性繫結在單一方向上將值從元件的屬性送到目標元素的屬性。

Property binding moves a value in one direction, from a component's property into a target element property.

有關偵聽事件的更多資訊,請參閱事件繫結

For more information on listening for events, see Event binding.

要讀取目標元素的屬性或呼叫其方法,請參閱 ViewChildContentChild 的 API 參考手冊。

To read a target element property or call one of its methods, see the API reference for ViewChild and ContentChild.

繫結到屬性

Binding to a property

要繫結到元素的屬性,請將其括在方括號 [] 內,該括號會將屬性標為目標屬性。目標屬性就是你要對其進行賦值的 DOM 屬性。例如,以下程式碼中的目標屬性是 img 元素的 src 屬性。

To bind to an element's property, enclose it in square brackets, [], which identifies the property as a target property. A target property is the DOM property to which you want to assign a value. For example, the target property in the following code is the image element's src property.

<img [src]="itemImageUrl">
src/app/app.component.html
      
      <img [src]="itemImageUrl">
    

在大多數情況下,目標的名稱就是 Property 的名稱,哪怕它看起來像 Attribute 的名稱。在此示例中,src 就是 <img> 元素的 Property 名稱。

In most cases, the target name is the name of a property, even when it appears to be the name of an attribute. In this example, src is the name of the <img> element property.

方括號 [] 使 Angular 將等號的右側看作動態表示式進行求值。如果不使用方括號,Angular 就會將右側視為字串字面量並將此屬性設定為該靜態值。

The brackets, [], cause Angular to evaluate the right-hand side of the assignment as a dynamic expression. Without the brackets, Angular treats the the right-hand side as a string literal and sets the property to that static value.

<app-item-detail childItem="parentItem"></app-item-detail>
src/app.component.html
      
      <app-item-detail childItem="parentItem"></app-item-detail>
    

省略方括號就會渲染出字串 parentItem,而不是 parentItem 的值。

Omitting the brackets renders the string parentItem, not the value of parentItem.

將元素的屬性設定為元件屬性的值

Setting an element property to a component property value

要將 <img>src 屬性繫結到元件的屬性,請將目標 src 放在方括號中,後跟等號,然後是元件的屬性。在這裡元件的屬性是 itemImageUrl

To bind the src property of an <img> element to a component's property, place the target, src, in square brackets followed by an equal sign and then the property. The property here is itemImageUrl.

<img [src]="itemImageUrl">
src/app/app.component.html
      
      <img [src]="itemImageUrl">
    

在元件類別 AppComponent 中宣告 itemImageUrl 屬性。

Declare the itemImageUrl property in the class, in this case AppComponent.

itemImageUrl = '../assets/phone.png';
src/app/app.component.ts
      
      itemImageUrl = '../assets/phone.png';
    

colspancolSpan

colspan and colSpan

最容易混淆的地方是 colspan 這個 Attribute 和 colSpan 這個 Property。請注意,這兩個名稱只有一個字母的大小寫不同。

A common point of confusion is between the attribute, colspan, and the property, colSpan. Notice that these two names differ by only a single letter.

如果你這樣寫:

If you wrote something like this:

<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
      
      <tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
    

你會收到此錯誤:

You'd get this error:

Template parse errors: Can't bind to 'colspan' since it isn't a known native property
      
      Template parse errors:
Can't bind to 'colspan' since it isn't a known native property
    

如訊息中所示,<td> 元素沒有 colspan Property。這是正確的,因為 colspan 是一個 Attribute — colSpan(帶大寫 S)才是相應的 Property。插值和 Property 繫結只能設定 Property,不能設定 Attribute。

As the message says, the <td> element does not have a colspan property. This is true because colspan is an attribute—colSpan, with a capital S, is the corresponding property. Interpolation and property binding can set only properties, not attributes.

相反,你應該使用 Property 繫結並將其編寫為:

Instead, you'd use property binding and write it like this:

<!-- Notice the colSpan property is camel case --> <tr><td [colSpan]="1 + 1">Three-Four</td></tr>
src/app/app.component.html
      
      <!-- Notice the colSpan property is camel case -->
<tr><td [colSpan]="1 + 1">Three-Four</td></tr>
    

另一個示例是在元件說它自己 isUnchanged 時禁用按鈕:

Another example is disabling a button when the component says that it isUnchanged:

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

另一個是設定指令的屬性:

Another is setting a property of a directive:

<p [ngClass]="classes">[ngClass] binding to the classes property making this blue</p>
src/app/app.component.html
      
      <p [ngClass]="classes">[ngClass] binding to the classes property making this blue</p>
    

還有一個是設定自訂元件的模型屬性,這是父元件和子元件進行通訊的一種好辦法:

Yet another is setting the model property of a custom component—a great way for parent and child components to communicate:

<app-item-detail [childItem]="parentItem"></app-item-detail>
src/app/app.component.html
      
      <app-item-detail [childItem]="parentItem"></app-item-detail>
    

切換按鈕功能

Toggling button functionality

若要根據布林值禁用按鈕的功能,請將 DOM 的 disabled Property 設定為類別中的源屬性(可能為 truefalse)。

To disable a button's functionality depending on a Boolean value, bind the DOM disabled property to a property in the class that is true or false.

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

由於 AppComponent 中屬性 isUnchanged 的值是 true,Angular 會禁用該按鈕。

Because the value of the property isUnchanged is true in the AppComponent, Angular disables the button.

isUnchanged = true;
src/app/app.component.ts
      
      isUnchanged = true;
    

設定指令的屬性

Setting a directive property

要設定指令的屬性,請將指令放在方括號中,例如 [ngClass],後跟等號和一個源屬性。在這裡,這個源屬性的值是 classes

To set a property of a directive, place the directive within square brackets , such as [ngClass], followed by an equal sign and the property. Here, the property is classes.

<p [ngClass]="classes">[ngClass] binding to the classes property making this blue</p>
src/app/app.component.html
      
      <p [ngClass]="classes">[ngClass] binding to the classes property making this blue</p>
    

要使用該屬性,必須在元件類別中宣告它,在這裡是 AppComponent。其 classes 的值是 special

To use the property, you must declare it in the class, which in this example is AppComponent. The value of classes is special.

classes = 'special';
src/app/app.component.ts
      
      classes = 'special';
    

Angular 會將 special 類別應用到 <p> 元素,以便你可以透過 special 來應用 CSS 樣式。

Angular applies the class special to the <p> element so that you can use special to apply CSS styles.

在元件之間繫結值

Bind values between components

要設定自訂元件的模型屬性,請將目標屬性(此處為 childItem)放在方括號 [] 中,其後跟著等號與源屬性。在這裡,這個源屬性是 parentItem

To set the model property of a custom component, place the target, here childItem, between square brackets [] followed by an equal sign and the property. Here, the property is parentItem.

<app-item-detail [childItem]="parentItem"></app-item-detail>
src/app/app.component.html
      
      <app-item-detail [childItem]="parentItem"></app-item-detail>
    

要使用目標和源屬性,必須在它們各自的類別中宣告它們。

To use the target and the property, you must declare them in their respective classes.

在元件類別(這裡是 ItemDetailComponent)中宣告 childItem 的目標。

Declare the target of childItem in its component class, in this case ItemDetailComponent.

例如,以下程式碼在其元件類別(這裡是 ItemDetailComponent)中聲明瞭 childItem 的目標。

For example, the following code declares the target of childItem in its component class, in this case ItemDetailComponent.

然後,程式碼包含一個帶有 @Input() 裝飾器的 childItem 屬性,這樣才能讓資料流入其中。

Then, the code contains an @Input() decorator with the childItem property so data can flow into it.

@Input() childItem: string;
src/app/item-detail/item-detail.component.ts
      
      @Input() childItem: string;
    

接下來,程式碼在其元件類別(這裡是 AppComponent)中宣告屬性 parentItem。在此示例中, childItem 的型別為 string ,因此 parentItem 也必須為字串。在這裡,parentItem 的字串值為 lamp

Next, the code declares the property of parentItem in its component class, in this case AppComponent. In this example the type of childItem is string, so parentItem needs to be a string. Here, parentItem has the string value of lamp.

parentItem = 'lamp';
src/app/app.component.ts
      
      parentItem = 'lamp';
    

這種配置方式下,<app-item-detail> 的檢視使用來自 childItem 的值 lamp

With this configuration, the view of <app-item-detail> uses the value of lamp for childItem.

屬性繫結與安全性

Property binding and security

屬性繫結可以幫助確保內容的安全。例如,考慮以下惡意內容。

Property binding can help keep content secure. For example, consider the following malicious content.

evilTitle = 'Template <script>alert("evil never sleeps")</script> Syntax';
src/app/app.component.ts
      
      evilTitle = 'Template <script>alert("evil never sleeps")</script> Syntax';
    

元件範本對內容進行插值,如下所示:

The component template interpolates the content as follows:

<p><span>"{{evilTitle}}" is the <i>interpolated</i> evil title.</span></p>
src/app/app.component.html
      
      <p><span>"{{evilTitle}}" is the <i>interpolated</i> evil title.</span></p>
    

瀏覽器不會處理 HTML,而是原樣顯示它,如下所示。

The browser doesn't process the HTML and instead displays it raw, as follows.

"Template <script>alert("evil never sleeps")</script> Syntax" is the interpolated evil title.
      
      "Template <script>alert("evil never sleeps")</script> Syntax" is the interpolated evil title.
    

Angular 不允許帶有 <script> 標記的 HTML,既不能用於插值也不能用於屬性繫結,這樣就會阻止執行 JavaScript。

Angular does not allow HTML with <script> tags, neither with interpolation nor property binding, which prevents the JavaScript from running.

但是,在以下示例中,Angular 在顯示值之前會先對它們進行無害化處理

In the following example, however, Angular sanitizes the values before displaying them.

<!-- Angular generates a warning for the following line as it sanitizes them WARNING: sanitizing HTML stripped some content (see https://g.co/ng/security#xss). --> <p>"<span [innerHTML]="evilTitle"></span>" is the <i>property bound</i> evil title.</p>
src/app/app.component.html
      
      <!--
 Angular generates a warning for the following line as it sanitizes them
 WARNING: sanitizing HTML stripped some content (see https://g.co/ng/security#xss).
-->
 <p>"<span [innerHTML]="evilTitle"></span>" is the <i>property bound</i> evil title.</p>
    

插值處理 <script> 標記的方式與屬性繫結的方式不同,但這兩種方法都可以使內容無害。以下是經過無害化處理的 evilTitle 示例的瀏覽器輸出。

Interpolation handles the <script> tags differently than property binding, but both approaches render the content harmlessly. The following is the browser output of the sanitized evilTitle example.

"Template Syntax" is the property bound evil title.
      
      "Template Syntax" is the property bound evil title.
    

屬性繫結和插值

Property binding and interpolation

通常,插值和屬性繫結可以達到相同的結果。以下繫結會做相同的事。

Often interpolation and property binding can achieve the same results. The following binding pairs do the same thing.

<p><img src="{{itemImageUrl}}"> is the <i>interpolated</i> image.</p> <p><img [src]="itemImageUrl"> is the <i>property bound</i> image.</p> <p><span>"{{interpolationTitle}}" is the <i>interpolated</i> title.</span></p> <p>"<span [innerHTML]="propertyTitle"></span>" is the <i>property bound</i> title.</p>
src/app/app.component.html
      
      <p><img src="{{itemImageUrl}}"> is the <i>interpolated</i> image.</p>
<p><img [src]="itemImageUrl"> is the <i>property bound</i> image.</p>

<p><span>"{{interpolationTitle}}" is the <i>interpolated</i> title.</span></p>
<p>"<span [innerHTML]="propertyTitle"></span>" is the <i>property bound</i> title.</p>
    

將資料值渲染為字串時,可以使用任一種形式,只是插值形式更易讀。但是,要將元素屬性設定為非字串資料值時,必須使用屬性繫結。

You can use either form when rendering data values as strings, though interpolation is preferable for readability. However, when setting an element property to a non-string data value, you must use property binding.


下一步是什麼

What's next