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

Directive

將類別標記為 Angular 指令的裝飾器。你可以定義自己的指令,以將自訂行為附加到 DOM 中的元素。

Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM.

檢視"說明"...

選項說明
selector?

這個 CSS 選擇器用於在範本中標記出該指令,並觸發該指令的實例化。

The CSS selector that identifies this directive in a template and triggers instantiation of the directive.

inputs?

列舉某個指令的一組可供資料繫結的輸入屬性

Enumerates the set of data-bound input properties for a directive

outputs?

列舉一組可供事件繫結的輸出屬性。

Enumerates the set of event-bound output properties.

providers?

一組依賴注入令牌,它允許 DI 系統為這個指令或元件提供依賴。

Configures the injector of this directive or component with a token that maps to a provider of a dependency.

exportAs?

定義一個名字,用於在範本中把該指令賦值給一個變數。

Defines the name that can be used in the template to assign this directive to a variable.

queries?

配置一些查詢,它們將被注入到該指令中。

Configures the queries that will be injected into the directive.

host?

使用一組鍵-值對,把類別的屬性對映到宿主元素的繫結(Property、Attribute 和事件)。

Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs.

jit?

如果存在,則該指令/元件將被 AOT 編譯器忽略。它會保留在發佈程式碼中,並且 JIT 編譯器會嘗試在執行時在瀏覽器中對其進行編譯。為了確保其行為正確,該應用程式必須匯入 @angular/compiler

When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import @angular/compiler.

子類別

說明

把一個類別標記為 Angular 指令。你可以定義自己的指令來為 DOM 中的元素新增自訂行為。 該選項提供配置元資料,用於決定該指令在執行期間要如何處理、實例化和使用。

The options provide configuration metadata that determines how the directive should be processed, instantiated and used at runtime.

像元件類別一樣,指令類別也可以實現生命週期鉤子,以影響它們的配置和行為。

Directive classes, like component classes, can implement life-cycle hooks to influence their configuration and behavior.

選項

這個 CSS 選擇器用於在範本中標記出該指令,並觸發該指令的實例化。

The CSS selector that identifies this directive in a template and triggers instantiation of the directive.

selector?: string
      
      selector?: string
    

可使用下列形式之一:

Declare as one of the following:

  • element-name:根據元素名選取。

    element-name: Select by element name.

  • .class:根據類別名稱選取。

    .class: Select by class name.

  • [attribute]:根據屬性名選取。

    [attribute]: Select by attribute name.

  • [attribute=value]:根據屬性名和屬性值選取。

    [attribute=value]: Select by attribute name and value.

  • :not(sub_selector):只有當元素不匹配子選擇器 sub_selector 的時候才選取。

    :not(sub_selector): Select only if the element does not match the sub_selector.

  • selector1, selector2:無論 selector1 還是 selector2 匹配時都選取。

    selector1, selector2: Select if either selector1 or selector2 matches.

Angular 的指令只允許那些不跨元素邊界的 CSS 選擇器。

Angular only allows directives to apply on CSS selectors that do not cross element boundaries.

對於下列範本 HTML,帶有 input[type=text] 選擇器的指令只會在 <input type="text"> 元素上實例化。

For the following template HTML, a directive with an input[type=text] selector, would be instantiated only on the <input type="text"> element.

<form> <input type="text"> <input type="radio"> <form>
      
      <form>
  <input type="text">
  <input type="radio">
<form>
    

列舉某個指令的一組可供資料繫結的輸入屬性

Enumerates the set of data-bound input properties for a directive

inputs?: string[]
      
      inputs?: string[]
    

Angular 會在變更檢測期間自動更新輸入屬性。 inputs 屬性定義了一組從 directiveProperty 指向 bindingProperty 的配置項:

Angular automatically updates input properties during change detection. The inputs property defines a set of directiveProperty to bindingProperty configuration:

  • directiveProperty 用於指定要寫入值的指令內屬性。

    directiveProperty specifies the component property where the value is written.

  • bindingProperty 用於指定要從中讀取值的 DOM 屬性。

    bindingProperty specifies the DOM property where the value is read from.

當沒有提供 bindingProperty 時,就假設它和 directiveProperty 一樣。

When bindingProperty is not provided, it is assumed to be equal to directiveProperty.

下面的例子建立了一個帶有兩個可繫結屬性的元件。

The following example creates a component with two data-bound properties.

@Component({ selector: 'bank-account', inputs: ['bankName', 'id: account-id'], template: ` Bank Name: {{bankName}} Account Id: {{id}} ` }) class BankAccount { bankName: string; id: string; }
      
      @Component({
  selector: 'bank-account',
  inputs: ['bankName', 'id: account-id'],
  template: `
    Bank Name: {{bankName}}
    Account Id: {{id}}
  `
})
class BankAccount {
  bankName: string;
  id: string;
}
    

列舉一組可供事件繫結的輸出屬性。

Enumerates the set of event-bound output properties.

outputs?: string[]
      
      outputs?: string[]
    

當輸出屬性發出一個事件時,就會呼叫範本中附加到它的一個事件處理器。

When an output property emits an event, an event handler attached to that event in the template is invoked.

outputs 屬性定義了一組從 directiveProperty 指向 bindingProperty 的配置項:

The outputs property defines a set of directiveProperty to bindingProperty configuration:

  • directiveProperty 用於指定要發出事件的指令屬性。

    directiveProperty specifies the component property that emits events.

  • bindingProperty 用於指定要附加事件處理器的 DOM 屬性。

    bindingProperty specifies the DOM property the event handler is attached to.

@Component({ selector: 'child-dir', outputs: [ 'bankNameChange' ] template: `<input (input)="bankNameChange.emit($event.target.value)" />` }) class ChildDir { bankNameChange: EventEmitter<string> = new EventEmitter<string>(); } @Component({ selector: 'main', template: ` {{ bankName }} <child-dir (bankNameChange)="onBankNameChange($event)"></child-dir> ` }) class MainComponent { bankName: string; onBankNameChange(bankName: string) { this.bankName = bankName; } }
      
      @Component({
  selector: 'child-dir',
  outputs: [ 'bankNameChange' ]
  template: `<input (input)="bankNameChange.emit($event.target.value)" />`
})
class ChildDir {
 bankNameChange: EventEmitter<string> = new EventEmitter<string>();
}

@Component({
  selector: 'main',
  template: `
    {{ bankName }} <child-dir (bankNameChange)="onBankNameChange($event)"></child-dir>
  `
})
class MainComponent {
 bankName: string;

  onBankNameChange(bankName: string) {
    this.bankName = bankName;
  }
}
    

一組依賴注入令牌,它允許 DI 系統為這個指令或元件提供依賴。

Configures the injector of this directive or component with a token that maps to a provider of a dependency.

providers?: Provider[]
      
      providers?: Provider[]
    

定義一個名字,用於在範本中把該指令賦值給一個變數。

Defines the name that can be used in the template to assign this directive to a variable.

exportAs?: string
      
      exportAs?: string
    
@Directive({ selector: 'child-dir', exportAs: 'child' }) class ChildDir { } @Component({ selector: 'main', template: `<child-dir #c="child"></child-dir>` }) class MainComponent { }
      
      @Directive({
  selector: 'child-dir',
  exportAs: 'child'
})
class ChildDir {
}

@Component({
  selector: 'main',
  template: `<child-dir #c="child"></child-dir>`
})
class MainComponent {
}
    

配置一些查詢,它們將被注入到該指令中。

Configures the queries that will be injected into the directive.

queries?: { [key: string]: any; }
      
      queries?: {
    [key: string]: any;
}
    

內容查詢會在呼叫 ngAfterContentInit 回呼(Callback)之前設定好。

Content queries are set before the ngAfterContentInit callback is called. View queries are set before the ngAfterViewInit callback is called.

下面的範例展示了如何定義這些查詢以及到生命週期鉤子中的哪個步驟才會有結果:

The following example shows how queries are defined and when their results are available in lifecycle hooks:

@Component({ selector: 'someDir', queries: { contentChildren: new ContentChildren(ChildDirective), viewChildren: new ViewChildren(ChildDirective) }, template: '<child-directive></child-directive>' }) class SomeDir { contentChildren: QueryList<ChildDirective>, viewChildren: QueryList<ChildDirective> ngAfterContentInit() { // contentChildren is set } ngAfterViewInit() { // viewChildren is set } }
      
      @Component({
  selector: 'someDir',
  queries: {
    contentChildren: new ContentChildren(ChildDirective),
    viewChildren: new ViewChildren(ChildDirective)
  },
  template: '<child-directive></child-directive>'
})
class SomeDir {
  contentChildren: QueryList<ChildDirective>,
  viewChildren: QueryList<ChildDirective>

  ngAfterContentInit() {
    // contentChildren is set
  }

  ngAfterViewInit() {
    // viewChildren is set
  }
}
    

使用一組鍵-值對,把類別的屬性對映到宿主元素的繫結(Property、Attribute 和事件)。

Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs.

host?: { [key: string]: string; }
      
      host?: {
    [key: string]: string;
}
    

Angular 在變更檢測期間會自動檢查宿主 Property 繫結。 如果繫結的值發生了變化,Angular 就會更新該指令的宿主元素。

Angular automatically checks host property bindings during change detection. If a binding changes, Angular updates the directive's host element.

當 key 是宿主元素的 Property 時,這個 Property 值就會傳播到指定的 DOM 屬性。

When the key is a property of the host element, the property value is the propagated to the specified DOM property.

當 key 是 DOM 中的靜態 Attribute 時,這個 Attribute 值就會傳播到宿主元素上指定的 Property 去。

When the key is a static attribute in the DOM, the attribute value is propagated to the specified property in the host element.

對於事件處理:

For event handling:

  • 它的 key 就是該指令想要監聽的 DOM 事件。 要想監聽全域性事件,請把要監聽的目標新增到事件名的前面。 這個目標可以是 windowdocumentbody

    The key is the DOM event that the directive listens to. To listen to global events, add the target to the event name. The target can be window, document or body.

  • 它的 value 就是當該事件發生時要執行的語句。如果該語句返回 false,那麼就會呼叫這個 DOM 事件的 preventDefault 函式。 這個語句中可以參考區域性變數 $event 來獲取事件資料。

    The value is the statement to execute when the event occurs. If the statement evaluates to false, then preventDefault is applied on the DOM event. A handler method can refer to the $event local variable.

如果存在,則該指令/元件將被 AOT 編譯器忽略。它會保留在發佈程式碼中,並且 JIT 編譯器會嘗試在執行時在瀏覽器中對其進行編譯。為了確保其行為正確,該應用程式必須匯入 @angular/compiler

When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import @angular/compiler.

jit?: true
      
      jit?: true
    

使用說明

要想定義一個指令,請為該類別加上此裝飾器,並提供元資料。

To define a directive, mark the class with the decorator and provide metadata.

import {Directive} from '@angular/core'; @Directive({ selector: 'my-directive', }) export class MyDirective { ... }
      
      import {Directive} from '@angular/core';

@Directive({
  selector: 'my-directive',
})
export class MyDirective {
...
}
    

宣告指令

Declaring directives

指令是可宣告物件。 它們必須在 NgModule 中宣告之後,才能用在應用中。

Directives are declarables. They must be declared by an NgModule in order to be usable in an app.

指令應當且只能屬於一個 NgModule。不要重新宣告那些從其它模組中匯入的指令。 請把該指令類別列在 NgModule 的 declarations 欄位中。

A directive must belong to exactly one NgModule. Do not re-declare a directive imported from another module. List the directive class in the declarations field of an NgModule.

declarations: [ AppComponent, MyDirective ],
      
      declarations: [
 AppComponent,
 MyDirective
],