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

文字插值

Text interpolation

文字插值允許你將動態字串值合併到 HTML 範本中。透過插值,你可以動態更改應用檢視中顯示的內容,例如顯示包含使用者名稱的自訂問候語。

Text interpolation allows you to incorporate dynamic string values into your HTML templates. With interpolation, you can dynamically change what appears in an application view, such as displaying a custom greeting that includes the user's name.

要了解本指南中涉及的語法和程式碼片段,請參閱現場演練 / 下載範例

See the現場演練 / 下載範例for all of the syntax and code snippets in this guide.

使用插值語法顯示值

Displaying values with interpolation

插值是指將表示式嵌入到被標記的文字中。預設情況下,插值使用雙花括號 {{}} 作為定界符。

Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters.

為了說明插值的工作原理,請考慮一個包含 currentCustomer 變數的 Angular 元件:

To illustrate how interpolation works, consider an Angular component that contains a currentCustomer variable:

src/app/app.component.ts
      
      currentCustomer = 'Maria';
    

你可以使用插值在相應的元件範本中顯示此變數的值:

You can use interpolation to display the value of this variable in the corresponding component template:

src/app/app.component.html
      
      <h3>Current customer: {{ currentCustomer }}</h3>
    

Angular 會用相應元件屬性的字串值替換掉 currentCustomer。在這裡,它的值是 Maria

Angular replaces currentCustomer with the string value of the corresponding component property. In this case, the value is Maria.

在以下示例中,Angular 會求出 titleitemImageUrl 屬性的值,以顯示一些標題文字和影象。

In the following example, Angular evaluates the title and itemImageUrl properties to display some title text and an image.

src/app/app.component.html
      
      <p>{{title}}</p>
<div><img src="{{itemImageUrl}}"></div>
    

範本表示式

Template expressions

範本表示式會產生一個值,它出現在雙花括號 {{ }} 中。 Angular 解析該表示式並將其賦值給繫結目標的某個屬性。目標可以是 HTML 元素、元件或指令。

A template expression produces a value and appears within double curly braces, {{ }}. Angular resolves the expression and assigns it to a property of a binding target. The target could be an HTML element, a component, or a directive.

用插值解析表示式

Resolving expressions with interpolation

一般來說,括號間的文字是一個範本表示式,Angular 先對它求值,再把它轉換成字串。 下列插值透過把括號中的兩個數字相加說明了這一點:

More generally, the text 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 two numbers:

src/app/app.component.html
      
      <!-- "The sum of 1 + 1 is 2" -->
<p>The sum of 1 + 1 is {{1 + 1}}.</p>
    

這些表示式也可以呼叫宿主元件的方法,就像下面用的 getVal()

Expressions can also invoke methods of the host component such as getVal() in the following example:

src/app/app.component.html
      
      <!-- "The sum of 1 + 1 is not 4" -->
<p>The sum of 1 + 1 is not {{1 + 1 + getVal()}}.</p>
    

透過插值,Angular 執行以下任務:

With interpolation, Angular performs the following tasks:

  1. 計算所有位於雙花括號中的表示式。

    Evaluates all expressions in double curly braces.

  2. 將這些表示式的結果轉換為字串。

    Converts the expression results to strings.

  3. 將這些結果融入相鄰的字串文字中。

    Links the results to any adjacent literal strings.

  4. 將融合後的結果賦值給元素或指令的屬性。

    Assigns the composite to an element or directive property.

如果你想用別的分隔符來代替 {{}},也可以透過 @Component() 元資料中的 interpolation 選項來配置插值分隔符。

You can configure the interpolation delimiter with the interpolation option in the @Component() metadata.

語法

Syntax

範本表示式和 JavaScript 很相似。許多 JavaScript 表示式都是合法的範本表示式,但以下情況除外。

Template expressions are similar to JavaScript. Many JavaScript expressions are legal template expressions, with the following exceptions.

你不能使用那些具有或可能引發副作用的 JavaScript 表示式,包括:

You can't use JavaScript expressions that have or promote side effects, including:

  • 賦值 (=, +=, -=, ...)

    Assignments (=, +=, -=, ...)

  • 運算子,比如 newtypeofinstanceof 等。

    Operators such as new, typeof, or instanceof

  • 使用 ;, 串聯起來的表示式

    Chaining expressions with ; or ,

  • 自增和自減運算子:++--

    The increment and decrement operators ++ and --

  • 一些 ES2015+ 版本的運算子

    Some of the ES2015+ operators

和 JavaScript 語法的其它顯著差異包括:

Other notable differences from JavaScript syntax include:

表示式上下文

Expression context

插值表示式具有上下文 —— 表示式所屬應用中的特定部分。通常,此上下文就是元件實例。

Interpolated expressions have a context—a particular part of the application to which the expression belongs. Typically, this context is the component instance.

在下面的程式碼片段中,表示式 recommendeditemImageUrl2 表示式所參考的都是 AppComponent 中的屬性。

In the following snippet, the expression recommended and the expression itemImageUrl2 refer to properties of the AppComponent.

src/app/app.component.html
      
      <h4>{{recommended}}</h4>
<img [src]="itemImageUrl2">
    

表示式也可以參考範本上下文中的屬性,例如範本輸入變數範本參考變數

An expression can also refer to properties of the template's context such as a template input variable or a template reference variable.

下面的例子就使用了範本輸入變數 customer

The following example uses a template input variable of customer.

src/app/app.component.html (template input variable)
      
      <ul>
  <li *ngFor="let customer of customers">{{customer.name}}</li>
</ul>
    

接下來的例子使用了範本參考變數 #customerInput

This next example features a template reference variable, #customerInput.

src/app/app.component.html (template reference variable)
      
      <label>Type something:
  <input #customerInput>{{customerInput.value}}
</label>
    

範本表示式不能參考全域性名稱空間中的任何東西,比如 windowdocument。它們也不能呼叫 console.logMath.max。 它們只能參考表示式上下文中的成員。

Template expressions cannot refer to anything in the global namespace, except undefined. They can't refer to window or document. Additionally, they can't call console.log() or Math.max() and they are restricted to referencing members of the expression context.

防止命名衝突

Preventing name collisions

表示式求值的上下文是範本變數、指令的上下文物件(如果有的話)以及元件成員的並集。如果所參考的名稱在多個名稱空間都有,則 Angular 將應用以下邏輯來確定上下文:

The context against which an expression evaluates is the union of the template variables, the directive's context object—if it has one—and the component's members. If you reference a name that belongs to more than one of these namespaces, Angular applies the following logic to determine the context:

  1. 範本變數的名稱。

    The template variable name.

  2. 指令上下文中的名稱。

    A name in the directive's context.

  3. 元件成員的名稱。

    The component's member names.

為避免變數遮蓋另一個上下文中的變數,請保持變數名稱唯一。在以下示例中,AppComponent 範本在問候 customer Padma。

To avoid variables shadowing variables in another context, keep variable names unique. In the following example, the AppComponent template greets the customer, Padma.

然後,一個 ngFor 列出了 customers 陣列中的每個 customer

An ngFor then lists each customer in the customers array.

src/app/app.component.ts
      
      @Component({
  template: `
    <div>
      <!-- Hello, Padma -->
      <h1>Hello, {{customer}}</h1>
      <ul>
        <!-- Ebony and Chiho in a list-->
        <li *ngFor="let customer of customers">{{ customer.value }}</li>
      </ul>
    </div>
  `
})
class AppComponent {
  customers = [{value: 'Ebony'}, {value: 'Chiho'}];
  customer = 'Padma';
}
    

ngFor 中的 customer 處於一個 <ng-template> 的上下文中,所以它指向的是 customers 陣列中的 customer,在這裡是 Ebony 和 Chiho。此列表中不包含 Padma,因為那個 customer 位於 ngFor 以外的另一個上下文中。反之,<h1> 中的 customer 不包括 Ebony 或 Chiho,因為該 customer 的上下文是元件類別,而這個類別中 customer 的值是 Padma。

The customer within the ngFor is in the context of an <ng-template> and so refers to the customer in the customers array, in this case Ebony and Chiho. This list does not feature Padma because customer outside of the ngFor is in a different context. Conversely, customer in the <h1> doesn't include Ebony or Chiho because the context for this customer is the class and the class value for customer is Padma.

表示式最佳實踐

Expression best practices

使用範本表示式時,請遵循以下最佳實踐:

When using template expressions, follow these best practices:

  • 使用短表示式

    Use short expressions

    儘可能使用屬性名稱或方法呼叫。將應用和業務邏輯保留在易於開發和測試的元件中。

    Use property names or method calls whenever possible. Keep application and business logic in the component, where it is easier to develop and test.

  • 快速執行

    Quick execution

    Angular 會在每個變更檢測週期之後執行範本表示式。許多非同步活動都會觸發變更檢測週期,例如解析 Promise、HTTP 結果、計時器事件、按鍵和滑鼠移動。

    Angular executes template expressions after every change detection cycle. Many asynchronous activities trigger change detection cycles, such as promise resolutions, HTTP results, timer events, key presses and mouse moves.

    表示式應儘快完成,以保持使用者體驗的效能,尤其是在速度較慢的裝置上。當計算值需要更多資源時,請考慮快取值。

    Expressions should finish quickly to keep the user experience as efficient as possible, especially on slower devices. Consider caching values when their computation requires greater resources.

  • 沒有可見的副作用

    No visible side effects

    根據 Angular 的單向資料流模型,除了目標屬性的值之外,範本表示式不應更改任何應用狀態。讀取元件值不應更改其他顯示值。該檢視應在整個渲染過程中保持穩定。

    According to Angular's unidirectional data flow model, a template expression should not change any application state other than the value of the target property. Reading a component value should not change some other displayed value. The view should be stable throughout a single rendering pass.

    冪等表示式能減少副作用
    Idempotent expressions reduce side effects

    冪等的表示式是最理想的,因為它沒有副作用,並且可以提高 Angular 的變更檢測效能。 用 Angular 術語來說,冪等表示式總會返回完全相同的東西,除非其依賴值之一發生了變化。

    An idempotent expression is free of side effects and improves Angular's change detection performance. In Angular terms, an idempotent expression always returns exactly the same thing until one of its dependent values changes.

在單獨的一次事件迴圈中,被依賴的值不應該改變。 如果冪等的表示式返回一個字串或數字,如果連續呼叫它兩次,會返回相同的字串或數字。 如果冪等的表示式返回一個物件(包括 DateArray),如果連續呼叫它兩次,會返回同一個物件的參考

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 if you call it twice consecutively. If the expression returns an object, including an array, it returns the same object reference if you call it twice consecutively.

對於 *ngFor,這種行為有一個例外。*ngFor 具有 trackBy 功能,在迭代物件時它可以正確處理物件值的變化。詳情參見 trackBy 的 *ngFor

There is one exception to this behavior that applies to *ngFor. *ngFor has trackBy functionality that can deal with changing values in objects when iterating over them. See *ngFor with trackByfor details.