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

Attribute 繫結、類別繫結和樣式繫結

Attribute, class, and style bindings

Angular 中的 Attribute 繫結可幫助你直接設定 Attribute 值。使用 Attribute 繫結,你可以提升無障礙性、動態設定應用程式樣式以及同時管理多個 CSS 類別或樣式。

Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.

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

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

繫結到 Attribute

Binding to an attribute

建議你儘可能設定帶有 Property 繫結的元素的 Property。但是,有時你沒有可繫結的元素 Property。在這種情況下,可以使用 Attribute 繫結。

It is recommended that you set an element property with a property binding whenever possible. However, sometimes you don't have an element property to bind. In those situations, you can use attribute binding.

例如,ARIASVG 只有 Attribute。 ARIA 和 SVG 都不對應於元素的 Property,也不設定元素的 Property。在這些情況下,必須使用 Attribute 繫結,因為沒有相應的目標 Property。

For example, ARIA and SVG are purely attributes. Neither ARIA nor SVG correspond to element properties and don't set element properties. In these cases, you must use attribute binding because there are no corresponding property targets.

語法

Syntax

Attribute 繫結語法類似於 Property 繫結,但不是直接在方括號之間放置元素的 Property,而是在 Attribute 名稱前面加上字首 attr,後跟一個點 .。然後,使用解析為字串的表示式設定 Attribute 值。

Attribute binding syntax resembles property binding, but instead of an element property between brackets, you precede the name of the attribute with the prefix attr, followed by a dot. Then, you set the attribute value with an expression that resolves to a string.

      
      <p [attr.attribute-you-are-targeting]="expression"></p>
    

當表示式解析為 nullundefined 時,Angular 會完全刪除該 Attribute。

When the expression resolves to null or undefined, Angular removes the attribute altogether.

繫結 ARIA Attribute

Binding ARIA attributes

Attribute 繫結的主要用例之一是設定 ARIA Attribute,如下所示:

One of the primary use cases for attribute binding is to set ARIA attributes, as in this example:

src/app/app.component.html
      
      <!-- create and set an aria attribute for assistive technology -->
<button [attr.aria-label]="actionName">{{actionName}} with Aria</button>
    

繫結到 colspan

Binding to colspan

Attribute 繫結的另一個常見用例是繫結到表格中的 colspan Attribute。colspan Attribute 可幫助你以程式設計方式讓表格保持動態。根據應用中用來填充表的資料量,某一行要跨越的列數可能會發生變化。

Another common use case for attribute binding is with the colspan attribute in tables. Binding to the colspan attribute helps you keep your tables programmatically dynamic. Depending on the amount of data that your application populates a table with, the number of columns that a row spans could change.

要將 Attribute 繫結到 <td>colspan Attribute:

To use attribute binding with the <td> attribute colspan:

  1. 使用以下語法指定 colspan[attr.colspan]

    Specify the colspan attribute by using the following syntax: [attr.colspan].

  2. [attr.colspan] 設定為等於某個表示式。

    Set [attr.colspan] equal to an expression.

在下面的示例中,我們將 colspan Attribute 繫結到表示式 1 + 1

In the following example, we bind the colspan attribute to the expression 1 + 1.

src/app/app.component.html
      
      <!--  expression calculates colspan=2 -->
<tr><td [attr.colspan]="1 + 1">One-Two</td></tr>
    

此繫結會導致 <tr> 跨越兩列。

This binding causes the <tr> to span two columns.

有時,Property 名和 Attribute 名之間存在差異。

Sometimes there are differences between the name of property and an attribute.

colspan<tr> 的 Attribute,而 colSpan(注意 “S” 是大寫)是 Property。使用 Attribute 繫結時,請使用帶小寫 “s” 的 colspan。有關如何繫結到 colSpan Property 的更多資訊,請參見 Property 繫結 中的 colspancolSpan部分。

colspan is an attribute of <tr>, while colSpan with a capital "S" is a property. When using attribute binding, use colspan with a lowercase "s". For more information on how to bind to the colSpan property, see the colspan and colSpansection of Property Binding.

繫結到 class Attribute

Binding to the class attribute

你可以使用類別繫結從元素的 class Attribute 中新增和刪除 CSS 類別名稱稱。

You can use class binding to add and remove CSS class names from an element's class attribute.

繫結到單個 CSS class

Binding to a single CSS class

要建立單個類別繫結,請使用字首 class 後跟一個點和 CSS 類別的名稱,例如 [class.sale]="onSale"onSale 為真值時新增類別,在表示式為假值時(undefined 除外)刪除類別。欲知詳情,請參見樣式委託部分。

To create a single class binding, use the prefix class followed by a dot and the name of the CSS class—for example, [class.sale]="onSale". Angular adds the class when the bound expression, onSale is truthy, and it removes the class when the expression is falsy—with the exception of undefined. See styling delegation for more information.

繫結到多個 CSS 類別

Binding to multiple CSS classes

要繫結到多個類別,請使用 [class] 來設定表示式 - 例如,[class]="classExpression",此表示式可以取如下值:

To bind to multiple classes, use [class] set to an expression—for example, [class]="classExpression". The expression can be one of:

  • 用空格分隔的類別名稱字串

    A space-delimited string of class names.

  • 以類別名稱作為鍵名並將真或假表示式作為值的物件。

    An object with class names as the keys and truthy or falsy expressions as the values.

  • 類別名稱的陣列。

    An array of class names.

對於物件格式,Angular 會在其關聯的值為真時才新增類別。

With the object format, Angular adds a class only if its associated value is truthy.

對於任何類似物件的表示式(例如 objectArrayMapSet,必須更改物件的參考,Angular 才能更新類別列表。在不更改物件參考的情況下只更新其 Attribute 是不會生效的。

With any object-like expression—such as object, Array, Map, or Set—the identity of the object must change for Angular to update the class list. Updating the property without changing object identity has no effect.

如果同一類別名稱有多個繫結,Angular 會根據樣式優先順序來確定要使用的繫結。

If there are multiple bindings to the same class name, Angular uses styling precedence to determine which binding to use.

下表是各種類別繫結語法的小結。

The following table summarizes class binding syntax.

繫結型別

Binding Type

語法

Syntax

輸入型別

Input Type

範例輸入值

Example Input Values

單一類別繫結

Single class binding

[class.sale]="onSale"boolean | undefined | nulltrue, false

多重類別繫結

Multi-class binding

[class]="classExpression"string"my-class-1 my-class-2 my-class-3"
Record<string, boolean | undefined | null>{foo: true, bar: false}
Array<string>['foo', 'bar']

繫結到 style Attribute

Binding to the style attribute

你可以使用樣式繫結來動態設定樣式。

You can use style binding to set styles dynamically.

繫結到單一樣式

Binding to a single style

要建立對單個樣式的繫結,請使用字首 style 後跟一個點和 CSS style Attribute 的名稱,例如 [style.width]="width"。 Angular 會將該 Attribute 設定為繫結表示式的值,這個值通常是一個字串。(可選)你還可以新增單位擴充套件,例如 em% ,它的值需要數字型別。

To create a single style binding, use the prefix style followed by a dot and the name of the CSS style property—for example, [style.width]="width". Angular sets the property to the value of the bound expression, which is usually a string. Optionally, you can add a unit extension like em or %, which requires a number type.

你可以用中線格式camelCase 格式編寫樣式 Attribute 名。

You can write a style property name in either dash-case, or camelCase.

      
      <nav [style.background-color]="expression"></nav>

<nav [style.backgroundColor]="expression"></nav>
    

繫結到多個樣式

Binding to multiple styles

要切換多個樣式,請繫結到 [style] Attribute,例如 [style]="styleExpression"styleExpression 可以是如下格式之一:

To toggle multiple styles, bind to the [style] attribute—for example, [style]="styleExpression". The styleExpression can be one of:

  • 樣式的字串列表,例如 "width: 100px; height: 100px; background-color: cornflowerblue;"

    A string list of styles such as "width: 100px; height: 100px; background-color: cornflowerblue;".

  • 一個物件,其鍵名是樣式名,其值是樣式值,比如 {width: '100px', height: '100px', backgroundColor: 'cornflowerblue'}

    An object with style names as the keys and style values as the values, such as {width: '100px', height: '100px', backgroundColor: 'cornflowerblue'}.

注意,不支援把陣列繫結給 [style]

Note that binding an array to [style] is not supported.

當把 [style] 繫結到物件表示式時,該物件的參考必須改變,這樣 Angular 才能更新這個類別列表。在不改變物件參考的情況下更新其屬性值是不會生效的。

When binding [style] to an object expression, the identity of the object must change for Angular to update the class list. Updating the property without changing object identity has no effect.

單樣式和多樣式繫結示例

Single and multiple-style binding example

nav-bar.component.ts
      
      @Component({
  selector: 'app-nav-bar',
  template: `
<nav [style]='navStyle'>
  <a [style.text-decoration]="activeLinkStyle">Home Page</a>
  <a [style.text-decoration]="linkStyle">Login</a>
</nav>`
})
export class NavBarComponent {
  navStyle = 'font-size: 1.2rem; color: cornflowerblue;';
  linkStyle = 'underline';
  activeLinkStyle = 'overline';
  /* . . . */
}
    

如果同一個樣式 Attribute 有多個繫結,Angular 將使用樣式優先順序來確定要使用的繫結。

If there are multiple bindings to the same style attribute, Angular uses styling precedence to determine which binding to use.

下表是各種樣式繫結語法的小結。

The following table summarizes style binding syntax.

繫結型別

Binding Type

語法

Syntax

輸入屬性

Input Type

範例輸入值

Example Input Values

單一樣式繫結

Single style binding

[style.width]="width"string | undefined | null"100px"

帶單位的單一樣式繫結

Single style binding with units

[style.width.px]="width"number | undefined | null100

多重樣式繫結

Multi-style binding

[style]="styleExpression"string"width: 100px; height: 100px"
Record<string, string | undefined | null>{width: '100px', height: '100px'}

NgStyle指令可以用作代替直接繫結 [style] 的方法。但是,最好使用上述不用 NgStyle 的繫結語法,因為由於 Angular 中樣式繫結的改進,NgStyle 不再提供顯著價值,將來可能會被刪除。

The NgStyle directive can be used as an alternative to direct [style] bindings. However, using the above style binding syntax without NgStyle is preferred because due to improvements in style binding in Angular, NgStyle no longer provides significant value, and might eventually be removed in the future.

樣式優先順序

Styling Precedence

一個 HTML 元素可以將其 CSS 類別列表和樣式值繫結到多個源(例如,來自多個指令的宿主繫結)。

A single HTML element can have its CSS class list and style values bound to multiple sources (for example, host bindings from multiple directives).

當有多個到相同的類別名稱或樣式屬性的繫結時,Angular 使用一組優先規則來解決衝突並確定最終將哪些類別或樣式應用於元素。

When there are multiple bindings to the same class name or style property, Angular uses a set of precedence rules to resolve conflicts and determine which classes or styles are ultimately applied to the element.

樣式優先順序(從高到低)

Styling precedence (highest to lowest)

  1. 範本繫結

    Template bindings

    1. 屬性繫結(例如,<div [class.foo]="hasFoo"><div [style.color]="color">

      Property binding (for example, <div [class.foo]="hasFoo"> or <div [style.color]="color">)

    2. 對映表繫結(例如,<div [class]="classExpr"><div [style]="styleExpr">

      Map binding (for example, <div [class]="classExpr"> or <div [style]="styleExpr">)

    3. 靜態值(例如 <div class="foo"><div style="color: blue">

      Static value (for example, <div class="foo"> or <div style="color: blue">)

  2. 指令宿主繫結

    Directive host bindings

    1. 屬性繫結(例如,host: {'[class.foo]': 'hasFoo'}host: {'[style.color]': 'color'}

      Property binding (for example, host: {'[class.foo]': 'hasFoo'} or host: {'[style.color]': 'color'})

    2. 對映表繫結(例如,host: {'[class]': 'classExpr'}host: {'[style]': 'styleExpr'}

      Map binding (for example, host: {'[class]': 'classExpr'} or host: {'[style]': 'styleExpr'})

    3. 靜態值(例如,host: {'class': 'foo'}host: {'style': 'color: blue'}

      Static value (for example, host: {'class': 'foo'} or host: {'style': 'color: blue'})

  3. 元件宿主繫結

    Component host bindings

    1. 屬性繫結(例如,host: {'[class.foo]': 'hasFoo'}host: {'[style.color]': 'color'}

      Property binding (for example, host: {'[class.foo]': 'hasFoo'} or host: {'[style.color]': 'color'})

    2. 對映表繫結(例如,host: {'[class]': 'classExpr'}host: {'[style]': 'styleExpr'}

      Map binding (for example, host: {'[class]': 'classExpr'} or host: {'[style]': 'styleExpr'})

    3. 靜態值(例如,host: {'class': 'foo'}host: {'style': 'color: blue'}

      Static value (for example, host: {'class': 'foo'} or host: {'style': 'color: blue'})

總之,類別或樣式繫結越具體,其優先順序就越高。

The more specific a class or style binding is, the higher its precedence.

繫結到具體類別(例如 [class.foo] )將優先於不特定 [class] 的繫結,並且繫結到特定樣式(例如 [style.bar] )將優先於不特定 [style] 的繫結。

A binding to a specific class (for example, [class.foo]) will take precedence over a generic [class] binding, and a binding to a specific style (for example, [style.bar]) will take precedence over a generic [style] binding.

src/app/app.component.html
      
      <h3>Basic specificity</h3>

<!-- The `class.special` binding overrides any value for the `special` class in `classExpression`.  -->
<div [class.special]="isSpecial" [class]="classExpression">Some text.</div>

<!-- The `style.color` binding overrides any value for the `color` property in `styleExpression`.  -->
<div [style.color]="color" [style]="styleExpression">Some text.</div>
    

當涉及不同來源的繫結時,也適用這些特異性規則。元素可能具有在其宣告的範本中的繫結、在其匹配的指令中的宿主繫結、在其匹配的元件中的宿主繫結。

Specificity rules also apply when it comes to bindings that originate from different sources. It's possible for an element to have bindings in the template where it's declared, from host bindings on matched directives, and from host bindings on matched components.

範本繫結是最具體的,因為它們會直接且排他地應用於元素,因此它們具有最高的優先順序。

Template bindings are the most specific because they apply to the element directly and exclusively, so they have the highest precedence.

指令宿主繫結被認為不太具體,因為指令可以在多個位置使用,因此它們的優先順序低於範本繫結。

Directive host bindings are considered less specific because directives can be used in multiple locations, so they have a lower precedence than template bindings.

指令通常會增強元件的行為,因此元件的宿主繫結具有最低的優先順序。

Directives often augment component behavior, so host bindings from components have the lowest precedence.

src/app/app.component.html
      
      <h3>Source specificity</h3>

<!-- The `class.special` template binding overrides any host binding to the `special` class set by `dirWithClassBinding` or `comp-with-host-binding`.-->
<comp-with-host-binding [class.special]="isSpecial" dirWithClassBinding>Some text.</comp-with-host-binding>

<!-- The `style.color` template binding overrides any host binding to the `color` property set by `dirWithStyleBinding` or `comp-with-host-binding`. -->
<comp-with-host-binding [style.color]="color" dirWithStyleBinding>Some text.</comp-with-host-binding>
    

此外,繫結會優先於靜態屬性。

In addition, bindings take precedence over static attributes.

在這裡,class[class] 具有相似的特異性,但是 [class] 繫結更優先一些,因為它是動態的。

In the following case, class and [class] have similar specificity, but the [class] binding will take precedence because it is dynamic.

src/app/app.component.html
      
      <h3>Dynamic vs static</h3>

<!-- If `classExpression` has a value for the `special` class, this value overrides the `class="special"` below -->
<div class="special" [class]="classExpression">Some text.</div>

<!-- If `styleExpression` has a value for the `color` property, this value overrides the `style="color: blue"` below -->
<div style="color: blue" [style]="styleExpression">Some text.</div>
    

委託給優先順序較低的樣式

Delegating to styles with lower precedence

可以用 undefined 值來把高優先順序的樣式“委託”給較低優先順序的樣式。將樣式屬性設定為 null 可以確保樣式被刪除,而將其設定為 undefined 將導致 Angular 回退到該樣式的次高優先順序繫結。

It is possible for higher precedence styles to "delegate" to lower precedence styles using undefined values. Whereas setting a style property to null ensures the style is removed, setting it to undefined will cause Angular to fall back to the next-highest precedence binding to that style.

例如,考慮以下範本:

For example, consider the following template:

src/app/app.component.html
      
      <comp-with-host-binding dirWithHostBinding></comp-with-host-binding>
    

假設 dirWithHostBinding 指令和 comp-with-host-binding 元件都具有 [style.width] 宿主繫結。在這裡,如果 dirWithHostBinding 將其繫結設定為 undefined ,則 width 屬性將回退到 comp-with-host-binding 宿主繫結的值。但是,如果 dirWithHostBinding 將其繫結設定為 null ,則會完全刪除 width

Imagine that the dirWithHostBinding directive and the comp-with-host-binding component both have a [style.width] host binding. In that case, if dirWithHostBinding sets its binding to undefined, the width property will fall back to the value of the comp-with-host-binding host binding. However, if dirWithHostBinding sets its binding to null, the width property will be removed entirely.

注入屬性值

Injecting attribute values

在某些情況下,你需要根據在 host 元素上以 HTML 屬性的形式設定的靜態值來區分元件指令的行為。例如,你可能有一個指令,需要知道 <button><input> 元素的 type 值。

There are cases where you need to differentiate the behavior of a Component or Directive based on a static value set on the host element as an HTML attribute. For example, you might have a directive that needs to know the type of a <button> or <input> element.

Attribute引數裝飾器非常適合透過依賴注入來將 HTML 屬性的值傳遞給元件/指令建構函式。

The Attribute parameter decorator is great for passing the value of an HTML attribute to a component/directive constructor via dependency injection.

這裡注入的值將捕獲指定 HTML 屬性的當前值。將來對屬性值的修改不會反映到注入的值中。

The injected value captures the value of the specified HTML attribute at that moment. Future updates to the attribute value are not reflected in the injected value.

src/app/my-input-with-attribute-decorator.component.ts
      
      import { Attribute, Component } from '@angular/core';

@Component({
  selector: 'app-my-input-with-attribute-decorator',
  template: 'The type of the input is: {{ type }}'
})
export class MyInputWithAttributeDecoratorComponent {
  constructor(@Attribute('type') public type: string) { }
}
    
src/app/app.component.html
      
      <app-my-input-with-attribute-decorator type="number"></app-my-input-with-attribute-decorator>
    

在前面的示例中,app.component.html的結果為:The type of the input is: number

In the preceding example, the result of app.component.html is The type of the input is: number.

另一個示例是RouterOutlet指令,該指令利用 Attribute 裝飾器檢索每個路由插座上的唯一名稱。

Another example is the RouterOutlet directive, which makes use of the Attribute decorator to retrieve the unique name on each outlet.

@Attribute() vs @Input()

請記住,要持續追蹤 Attribute 的值並更新關聯的 Property 時,請使用 @Input()。若要將 HTML 屬性的值注入到元件或指令的建構函式中,請使用@Attribute()

Remember, use @Input() when you want to keep track of the attribute value and update the associated property. Use @Attribute() when you want to inject the value of an HTML attribute to a component or directive constructor.