填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

Directive

把一个类标记为 Angular 指令。你可以定义自己的指令来为 DOM 中的元素添加自定义行为。 该选项提供配置元数据,用于决定该指令在运行期间要如何处理、实例化和使用。

Marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM. The options provide configuration metadata that determines how the directive should be processed, instantiated and used at runtime.

查看"说明"...

选项说明
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

如果为 true,则该指令/组件将会被 AOT 编译器忽略,始终使用 JIT 编译。

If true, this directive/component will be skipped by the AOT compiler and so will always be compiled using JIT.

说明

像组件类一样,指令类也可以实现生命周期钩子,以影响它们的配置和行为。

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.

范例

Example

下面的例子创建了一个带有两个可绑定属性的组件。

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.

范例

Example

@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; } }
      
      
  1. @Component({
  2. selector: 'child-dir',
  3. outputs: [ 'bankNameChange' ]
  4. template: `<input (input)="bankNameChange.emit($event.target.value)" />`
  5. })
  6. class ChildDir {
  7. bankNameChange: EventEmitter<string> = new EventEmitter<string>();
  8. }
  9.  
  10. @Component({
  11. selector: 'main',
  12. template: `
  13. {{ bankName }} <child-dir (bankNameChange)="onBankNameChange($event)"></child-dir>
  14. `
  15. })
  16. class MainComponent {
  17. bankName: string;
  18.  
  19. onBankNameChange(bankName: string) {
  20. this.bankName = bankName;
  21. }
  22. }

一组依赖注入令牌,它允许 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
    

简单例子

Simple Example

@Directive({ selector: 'child-dir', exportAs: 'child' }) class ChildDir { } @Component({ selector: 'main', template: `<child-dir #c="child"></child-dir>` }) class MainComponent { }
      
      
  1. @Directive({
  2. selector: 'child-dir',
  3. exportAs: 'child'
  4. })
  5. class ChildDir {
  6. }
  7.  
  8. @Component({
  9. selector: 'main',
  10. template: `<child-dir #c="child"></child-dir>`
  11. })
  12. class MainComponent {
  13. }

配置一些查询,它们将被注入到该指令中。

Configures the queries that will be injected into the directive.

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

内容查询会在调用 ngAfterContentInit 回调之前设置好。 试图查询会在调用 ngAfterViewInit 回调之前设置好。

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

范例

Example

下面的范例展示了如何定义这些查询以及到生命周期钩子中的哪个步骤才会有结果:

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 } }
      
      
  1. @Component({
  2. selector: 'someDir',
  3. queries: {
  4. contentChildren: new ContentChildren(ChildDirective),
  5. viewChildren: new ViewChildren(ChildDirective)
  6. },
  7. template: '<child-directive></child-directive>'
  8. })
  9. class SomeDir {
  10. contentChildren: QueryList<ChildDirective>,
  11. viewChildren: QueryList<ChildDirective>
  12.  
  13. ngAfterContentInit() {
  14. // contentChildren is set
  15. }
  16.  
  17. ngAfterViewInit() {
  18. // viewChildren is set
  19. }
  20. }

使用一组键-值对,把类的属性映射到宿主元素的绑定(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.

如果为 true,则该指令/组件将会被 AOT 编译器忽略,始终使用 JIT 编译。

If true, this directive/component will be skipped by the AOT compiler and so will always be compiled using JIT.

jit: true
      
      jit: true
    

该属性用来支持未来的 Ivy 工作。

This exists to support future Ivy work and has no effect currently.

使用说明

要想定义一个指令,请为该类加上此装饰器,并提供元数据。

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
],