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

屬性型指令

Attribute directives

使用屬性型指令,可以更改 DOM 元素和 Angular 元件的外觀或行為。

With attribute directives, you can change the appearance or behavior of DOM elements and Angular components.

有關包含本指南中程式碼片段的有效示例,請參見現場演練 / 下載範例

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

建立屬性型指令

Building an attribute directive

本節將引導你建立“突出顯示”指令,該指令會將宿主元素的背景色設定為黃色。

This section walks you through creating a highlight directive that sets the background color of the host element to yellow.

  1. 要建立指令,請使用 CLI 命令 ng generate directive

    To create a directive, use the CLI command ng generate directive.

          
          ng generate directive highlight
        

    CLI 建立 src/app/highlight.directive.ts 以及相應的測試檔案 src/app/highlight.directive.spec.ts,並在 AppModule 中宣告此指令類別。

    The CLI creates src/app/highlight.directive.ts, a corresponding test file src/app/highlight.directive.spec.ts, and declares the directive class in the AppModule.

    CLI 產生預設的 src/app/highlight.directive.ts,如下所示:

    The CLI generates the default src/app/highlight.directive.ts as follows:

    src/app/highlight.directive.ts
          
          import { Directive } from '@angular/core';
    
    @Directive({
      selector: '[appHighlight]'
    })
    export class HighlightDirective {
      constructor() { }
    }
        

    @Directive() 裝飾器的配置屬性會指定指令的 CSS 屬性選擇器 [appHighlight]

    The @Directive() decorator's configuration property specifies the directive's CSS attribute selector, [appHighlight].

  2. @angular/core 匯入 ElementRefElementRefnativeElement 屬性會提供對宿主 DOM 元素的直接訪問許可權。

    Import ElementRef from @angular/core. ElementRef grants direct access to the host DOM element through its nativeElement property.

  3. 在指令的 constructor() 中新增 ElementRef注入對宿主 DOM 元素的參考,該元素就是 appHighlight 的作用目標。

    Add ElementRef in the directive's constructor() to inject a reference to the host DOM element, the element to which you apply appHighlight.

  4. HighlightDirective 類別中新增邏輯,將背景設定為黃色

    Add logic to the HighlightDirective class that sets the background to yellow.

    src/app/highlight.directive.ts
          
          import { Directive, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[appHighlight]'
    })
    export class HighlightDirective {
        constructor(el: ElementRef) {
           el.nativeElement.style.backgroundColor = 'yellow';
        }
    }
        

指令支援名稱空間。

Directives do not support namespaces.

src/app/app.component.avoid.html (unsupported)
      
      <p app:Highlight>This is invalid</p>
    

應用屬性型指令

Applying an attribute directive

  1. 要使用 HighlightDirective,請將 <p> 元素新增到 HTML 範本中,並以偽指令作為屬性。

    To use the HighlightDirective, add a <p> element to the HTML template with the directive as an attribute.

    src/app/app.component.html
          
          <p appHighlight>Highlight me!</p>
        

Angualr 會建立 HighlightDirective 類別的實例,並將 <p> 元素的參考注入到該指令的建構函式中,它會將 <p> 元素的背景樣式設定為黃色。

Angular creates an instance of the HighlightDirective class and injects a reference to the <p> element into the directive's constructor, which sets the <p> element's background style to yellow.

處理使用者事件

Handling user events

本節會展示如何檢測使用者何時將滑鼠移入或移出元素以及如何透過設定或清除突出顯示顏色來進行響應。

This section shows you how to detect when a user mouses into or out of the element and to respond by setting or clearing the highlight color.

  1. 從 '@angular/core' 匯入 HostListener

    Import HostListener from '@angular/core'.

    src/app/highlight.directive.ts (imports)
          
          import { Directive, ElementRef, HostListener } from '@angular/core';
        
  2. 新增兩個事件處理程式,它們會在滑鼠進入或離開時做出響應,每個事件處理程式都帶有 @HostListener() 裝飾器。

    Add two event handlers that respond when the mouse enters or leaves, each with the @HostListener() decorator.

    src/app/highlight.directive.ts (mouse-methods)
          
          @HostListener('mouseenter') onMouseEnter() {
      this.highlight('yellow');
    }
    
    @HostListener('mouseleave') onMouseLeave() {
      this.highlight('');
    }
    
    private highlight(color: string) {
      this.el.nativeElement.style.backgroundColor = color;
    }
        

    使用 @HostListener() 裝飾器,你可以訂閱本屬性型指令宿主 DOM 元素上的事件(在本例中是 <p>)。

    With the @HostListener() decorator, you can subscribe to events of the DOM element that hosts an attribute directive, the <p> in this case.

    處理程式會委託給一個輔助方法 highlight(),該方法會設定宿主 DOM 元素 el 的顏色。

    The handlers delegate to a helper method, highlight(), that sets the color on the host DOM element, el.

完整的指令如下:

The complete directive is as follows:

src/app/highlight.directive.ts
      
      @Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight('');
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }

}
    

當指標懸停在 p 元素上時,背景顏色就會出現;而當指標移出時,背景顏色就會消失。

The background color appears when the pointer hovers over the paragraph element and disappears as the pointer moves out.

將值傳遞給屬性型指令

Passing values into an attribute directive

本節將引導你在應用 HighlightDirective 時設定突出顯示顏色。

This section walks you through setting the highlight color while applying the HighlightDirective.

  1. highlight.directive.ts 中,從 @angular/core 匯入 Input

    In highlight.directive.ts, import Input from @angular/core.

    src/app/highlight.directive.ts (imports)
          
          import { Directive, ElementRef, HostListener, Input } from '@angular/core';
        
  2. 新增一個 appHighlight@Input() 屬性。

    Add an appHighlight @Input() property.

    src/app/highlight.directive.ts
          
          @Input() appHighlight = '';
        

    @Input() 裝飾器會將元資料新增到此類別,以便讓該指令的 appHighlight 屬性可用於繫結。

    The @Input() decorator adds metadata to the class that makes the directive's appHighlight property available for binding.

  3. app.component.ts,將 color 屬性新增到 AppComponent

    In app.component.ts, add a color property to the AppComponent.

    src/app/app.component.ts (class)
          
          export class AppComponent {
      color = 'yellow';
    }
        
  4. 要同時應用指令和顏色,請透過 appHighlight 指令選擇器使用屬性繫結,將其設定為 color

    To simultaneously apply the directive and the color, use property binding with the appHighlight directive selector, setting it equal to color.

    src/app/app.component.html (color)
          
          <p [appHighlight]="color">Highlight me!</p>
        

    [appHighlight] 屬性繫結執行兩項任務:

    The [appHighlight] attribute binding performs two tasks:

    • 將突出顯示指令應用於 <p> 元素

      applies the highlighting directive to the <p> element

    • 透過屬性繫結設定指令的突出顯示顏色

      sets the directive's highlight color with a property binding

透過使用者輸入來設定值

Setting the value with user input

本節指導你新增單選按鈕,將你選擇的顏色繫結到 appHighlight 指令。

This section guides you through adding radio buttons to bind your color choice to the appHighlight directive.

  1. 將標記新增到 app.component.html 以選擇顏色,如下所示:

    Add markup to app.component.html for choosing a color as follows:

    src/app/app.component.html (v2)
          
          <h1>My First Attribute Directive</h1>
    
    <h2>Pick a highlight color</h2>
    <div>
      <input type="radio" name="colors" (click)="color='lightgreen'">Green
      <input type="radio" name="colors" (click)="color='yellow'">Yellow
      <input type="radio" name="colors" (click)="color='cyan'">Cyan
    </div>
    <p [appHighlight]="color">Highlight me!</p>
        
  2. 修改 AppComponent.color,使其沒有初始值。

    Revise the AppComponent.color so that it has no initial value.

    src/app/app.component.ts (class)
          
          export class AppComponent {
      color = '';
    }
        
  3. 啟動本應用的開發伺服器,以驗證使用者可以透過單選按鈕選擇顏色。

    Serve your application to verify that the user can choose the color with the radio buttons.

繫結到第二個屬性

Binding to a second property

本節將指導你配置應用程式,以便開發人員可以設定預設顏色。

This section guides you through configuring your application so the developer can set the default color.

  1. 將第二個 Input() 屬性 defaultColor 新增到 HighlightDirective

    Add a second Input() property to HighlightDirective called defaultColor.

    src/app/highlight.directive.ts (defaultColor)
          
          @Input() defaultColor = '';
        
  2. 修改指令的 onMouseEnter,使其首先嚐試使用 highlightColor 進行突出顯示,然後嘗試 defaultColor,如果兩個屬性都 undefined,則變回 red

    Revise the directive's onMouseEnter so that it first tries to highlight with the highlightColor, then with the defaultColor, and falls back to red if both properties are undefined.

    src/app/highlight.directive.ts (mouse-enter)
          
          @HostListener('mouseenter') onMouseEnter() {
      this.highlight(this.highlightColor || this.defaultColor || 'red');
    }
        
  3. 若要繫結到 AppComponent.color 並回退為預設顏色“紫羅蘭(violet)”,請新增以下 HTML。在這裡,defaultColor 繫結沒有使用方括號 [],因為它是靜態的。

    To bind to the AppComponent.color and fall back to "violet" as the default color, add the following HTML. In this case, the defaultColor binding doesn't use square brackets, [], because it is static.

    src/app/app.component.html (defaultColor)
          
          <p [appHighlight]="color" defaultColor="violet">
      Highlight me too!
    </p>
        

    與元件一樣,你可以將指令的多個屬性繫結新增到宿主元素上。

    As with components, you can add multiple directive property bindings to a host element.

如果沒有預設顏色(defaultColor)繫結,則預設為紅色。當用戶選擇一種顏色時,所選的顏色將成為突出顯示的顏色。

The default color is red if there is no default color binding. When the user chooses a color the selected color becomes the active highlight color.

透過 NgNonBindable 停用 Angular 處理過程

Deactivating Angular processing with NgNonBindable

要防止在瀏覽器中進行表示式求值,請將 ngNonBindable 新增到宿主元素。ngNonBindable 會停用範本中的插值、指令和繫結。

To prevent expression evaluation in the browser, add ngNonBindable to the host element. ngNonBindable deactivates interpolation, directives, and binding in templates.

在下面的示例中,表示式 {{ 1 + 1 }} 的渲染方式會和在程式碼編輯器的一樣,而不會顯示 2

In the following example, the expression {{ 1 + 1 }} renders just as it does in your code editor, and does not display 2.

src/app/app.component.html
      
      <p>Use ngNonBindable to stop evaluation.</p>
<p ngNonBindable>This should not evaluate: {{ 1 + 1 }}</p>
    

ngNonBindable 應用於元素將停止對該元素的子元素的繫結。但是,ngNonBindable 仍然允許指令在應用 ngNonBindable 的元素上工作。在以下示例中,appHighlight 指令仍處於活躍狀態,但 Angular 不會對表示式 {{ 1 + 1 }} 求值。

Applying ngNonBindable to an element stops binding for that element's child elements. However, ngNonBindable still allows directives to work on the element where you apply ngNonBindable. In the following example, the appHighlight directive is still active but Angular does not evaluate the expression {{ 1 + 1 }}.

src/app/app.component.html
      
      <h3>ngNonBindable with a directive</h3>
<div ngNonBindable [appHighlight]="'yellow'">This should not evaluate: {{ 1 +1 }}, but will highlight yellow.
</div>
    

如果將 ngNonBindable 應用於父元素,則 Angular 會禁用該元素的子元素的任何插值和繫結,例如屬性繫結或事件繫結。

If you apply ngNonBindable to a parent element, Angular disables interpolation and binding of any sort, such as property binding or event binding, for the element's children.