属性型指令

An Attribute directive changes the appearance or behavior of a DOM element.

属性型指令用于改变一个 DOM 元素的外观或行为。

Contents

目录

试试在线例子

Directives overview

指令概览

There are three kinds of directives in Angular:

在 Angular 中有三种类型的指令:

  1. Components—directives with a template. 组件 — 拥有模板的指令
  2. Structural directives—change the DOM layout by adding and removing DOM elements. 结构型指令 — 通过添加和移除 DOM 元素改变 DOM 布局的指令
  3. Attribute directives—change the appearance or behavior of an element. 属性型指令 — 改变元素显示和行为的指令。

Components are the most common of the three directives. You saw a component for the first time in the QuickStart example.

组件是这三种指令中最常用的。 你在快速起步例子中第一次见到组件。

Structural Directives change the structure of the view. Two examples are NgFor and NgIf in the Template Syntax page.

结构型指令修改视图的结构。例如,NgForNgIf

Attribute directives are used as attributes of elements. The built-in NgStyle directive in the Template Syntax page, for example, can change several element styles at the same time.

属性型指令改变一个元素的外观或行为。例如,内置的 NgStyle 指令可以同时修改元素的多个样式。

Build a simple attribute directive

创建一个简单的属性型指令

An attribute directive minimally requires building a controller class annotated with @Directive, which specifies the selector that identifies the attribute. The controller class implements the desired directive behavior.

属性型指令至少需要一个带有@Directive装饰器的控制器类。该装饰器指定了一个用于标识属性的选择器。 控制器类实现了指令需要的指令行为。

This page demonstrates building a simple attribute directive to set an element's background color when the user hovers over that element.

本章展示了如何创建简单的属性型指令,在用户鼠标悬浮在一个元素上时,改变它的背景色

Technically, a directive isn't necessary to simply set the background color. Style binding can set styles as follows:

实际上,简单地设置背景颜色并不需要再定义一个指令。样式绑定可以像下面这样设置样式:

<p [style.background]="'lime'">I am green with envy!</p>

Read more about style binding on the Template Syntax page.

更多信息,见模板语法样式绑定

For a simple example, though, this will demonstrate how attribute directives work.

作为一个简单的例子,它展示了属性型指令是如何工作的。

Write the directive code

编写指令代码

Follow the setup instructions for creating a new project named attribute-directives.

按照开发环境的说明,创建一个项目文件夹attribute-directives

Create the following source file in the indicated folder with the following code:

在指定的文件夹下创建下列源码文件:

app/highlight.directive.ts

import { Directive, ElementRef, Input, Renderer } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { constructor(el: ElementRef, renderer: Renderer) { renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow'); } }

The import statement specifies symbols from the Angular core:

import语句指定了从 Angular 的core库导入的一些符号。

  1. Directive provides the functionality of the @Directive decorator.

    Directive提供@Directive装饰器功能。

  2. ElementRef injects into the directive's constructor so the code can access the DOM element.

    ElementRef注入到指令构造函数中。 这样代码可以访问 DOM 元素。

  3. Input allows data to flow from the binding expression into the directive.

    Input将数据从绑定表达式传达到指令中。

  4. Renderer allows the code to change the DOM element's style.

    Renderer 让代码可以改变 DOM 元素的样式。

Next, the @Directive decorator function contains the directive metadata in a configuration object as an argument.

然后,@Directive装饰器函数以配置对象参数的形式,包含了指令的元数据。

@Directive requires a CSS selector to identify the HTML in the template that is associated with the directive.

@Directive装饰器需要一个 CSS 选择器,以便从模板中识别出关联到这个指令的 HTML。

The CSS selector for an attribute is the attribute name in square brackets. Here, the directive's selector is [myHighlight]. Angular will locate all elements in the template that have an attribute named myHighlight.

用于 attribute 的 CSS 选择器就是属性名称加方括号。 这里,指令的选择器是[myHighlight],Angular 将会在模板中找到所有带myHighlight属性的元素。

Why not call it "highlight"?

为什么不直接叫做 "highlight"?

Though highlight is a more concise name than myHighlight and would work, a best practice is to prefix selector names to ensure they don't conflict with standard HTML attributes. This also reduces the risk colliding with third-party directive names.

尽管highlight 是一个比 myHighlight 更简洁的名字,而且它确实也能工作。 但是最佳实践是在选择器名字前面添加前缀,以确保它们不会与标准 HTML 属性冲突。 它同时减少了与第三方指令名字发生冲突的危险。

Make sure you do not prefix the highlight directive name with ng because that prefix is reserved for Angular and using it could cause bugs that are difficult to diagnose. For a simple demo, the short prefix, my, helps distinguish your custom directive.

确认你没有highlight指令添加ng前缀。 那个前缀属于 Angular,使用它可能导致难以诊断的 bug。例如,这个简短的前缀my可以帮助你区分自定义指令。

After the @Directive metadata comes the directive's controller class, called HighlightDirective, which contains the logic for the directive.Exporting HighlightDirective makes it accessible to other components.

@Directive元数据的后面就是指令的控制器类,叫做HighlightDirective,它包括了指令的工作逻辑。导出HighlightDirective以便让它可以被其它组件访问。

Angular creates a new instance of the directive's controller class for each matching element, injecting an Angular ElementRef and Renderer into the constructor. ElementRef is a service that grants direct access to the DOM element through its nativeElement property and Renderer allows the code to set the element style.

Angular 会为每个匹配的元素创建一个指令控制器类的实例,并把 Angular 的ElementRefRenderer注入进构造函数。 ElementRef是一个服务,它赋予我们通过它的nativeElement属性直接访问 DOM 元素的能力。 Renderer服务允许通过代码设置元素的样式。

Apply the attribute directive

使用属性型指令

To use the new HighlightDirective, create a template that applies the directive as an attribute to a paragraph (p) element. In Angular terms, the <p> element will be the attribute host.

要使用这个新的HighlightDirective,创建一个模板,把这个指令作为属性应用到一个段落(p)元素上。 用 Angular 的话说,<p>元素就是这个属性型指令的宿主

Put the template in its ownapp.component.htmlfile that looks like this:

我们把这个模板放到自己的app.component.html文件中,就像这样:

app/app.component.html

<h1>My First Attribute Directive</h1> <p myHighlight>Highlight me!</p>

Now reference this template in the AppComponent:

现在,在AppComponent中引用这个模板:

app/app.component.ts

import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'my-app', templateUrl: 'app.component.html' }) export class AppComponent { }

Next, add an import statement to fetch the Highlight directive and add that class to the declarations NgModule metadata. This way Angular recognizes the directive when it encounters myHighlight in the template.

接下来,添加了一个import语句来获得Highlight指令类,并把这个类添加到 NgModule 元数据的declarations数组中。 这样,当 Angular 在模板中遇到myHighlight时,就能认出这是指令了。

app/app.module.ts

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HighlightDirective } from './highlight.directive'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, HighlightDirective ], bootstrap: [ AppComponent ] }) export class AppModule { }

Now when the app runs, the myHighlight directive highlights the paragraph text.

运行应用,就会看到我们的指令确实高亮了段落中的文本。

First Highlight

Your directive isn't working?

你的指令没生效?

Did you remember to add the directive to the the declarations attribute of @NgModule? It is easy to forget!

你记着设置@NgModuledeclarations数组了吗?它很容易被忘掉。

Open the console in the browser tools and look for an error like this:

打开浏览器调试工具的控制台,会看到像这样的错误信息:

EXCEPTION: Template parse errors: Can't bind to 'myHighlight' since it isn't a known property of 'p'.

Angular detects that you're trying to bind to something but it doesn't know what, so it looks to the declarations metadata array. By specifying HighlightDirective in the array, Angular knows to check the import statements and from there, to go to highlight.directive.ts to find out what myHighlight does.

Angular 检测到你正在尝试绑定到某些东西,但它不认识。所以它在declarations元数据数组中查找。 把HighlightDirective列在元数据的这个数组中,Angular 就会检查对应的导入语句,从而找到highlight.directive.ts,并了解myHightlight的功能。

To summarize, Angular found the myHighlight attribute on the <p> element. It created an instance of the HighlightDirective class, injecting a reference to the element into the constructor where the <p> element's background style is set to yellow.

总结:Angular 在<p>元素上发现了一个myHighlight属性。 然后它创建了一个HighlightDirective类的实例,并把所在元素的引用注入到了指令的构造函数中。 在构造函数中,我们把<p>元素的背景设置为了黄色。

Respond to user-initiated events

响应用户引发的事件

Currently, myHighlight simply sets an element color. The directive should set the color when the user hovers over an element.

当前,myHighlight只是简单的设置元素的颜色。 这个指令应该在用户鼠标悬浮一个元素时,设置它的颜色。

This requires two things:

我们需要:

  1. detecting when the user hovers into and out of the element.

    检测用户的鼠标何时进入和离开这个元素。

  2. responding to those actions by setting and clearing the highlight color.

    通过设置和清除高亮色来响应这些操作。

To do this, you can apply the @HostListener decorator to methods which are called when an event is raised.

@HostListener装饰应用到事件触发时需调用的方法。

@HostListener('mouseenter') onMouseEnter() { /* . . . */ } @HostListener('mouseleave') onMouseLeave() { /* . . . */ }

The @HostListener decorator refers to the DOM element that hosts an attribute directive, the <p> in this case.

@HostListener装饰器引用属性型指令的宿主元素,在这个例子中就是<p>

It is possible to attach event listeners by manipulating the host DOM element directly, but

可以通过直接操纵 DOM 元素的方式给宿主 DOM 元素附加一个事件监听器,但是

there are at least three problems with such an approach:

但这种方法至少有三个问题:

  1. You have to write the listeners correctly.

    必须正确的书写事件监听器。

  2. The code must detach the listener when the directive is destroyed to avoid memory leaks.

    当指令被销毁的时候,必须拆卸事件监听器,否则会导致内存泄露。

  3. Talking to DOM API directly isn't a best practice.

    必须直接和 DOM API 打交道,应该避免这样做。

Now implement the two mouse event handlers:

现在,我们实现那两个鼠标事件处理器:

@HostListener('mouseenter') onMouseEnter() { this.highlight('yellow'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color); }

Notice that they delegate to a helper method that sets the color via a private local variable, el. Next, revise the constructor to capture the ElementRef.nativeElement in this variable.

注意,它们把处理逻辑委托给了一个辅助方法,这个方法会通过一个私有变量el来设置颜色。 我们要修改构造函数,来把ElementRef.nativeElement存进这个私有变量。

constructor(private el: ElementRef, private renderer: Renderer) { }

Here's the updated directive:

这里是更新过的指令:

app/highlight.directive.ts

import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer) { } @HostListener('mouseenter') onMouseEnter() { this.highlight('yellow'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color); } }

Run the app and confirm that the background color appears when the mouse hovers over the p and disappears as it moves out. We run the app and confirm that the background color appears as we move the mouse over the p and disappears as we move out.

运行本应用并确认:当把鼠标移到p上的时候,背景色就出现了,而移开的时候,它消失了。

Second Highlight

Pass values into the directive using data binding

使用数据绑定向指令传递值

Currently the highlight color is hard-coded within the directive. That's inflexible. A better practice is to set the color externally with a binding as follows:

现在的高亮颜色是在指令中硬编码进去的。这样没有弹性。 我们应该通过绑定从外部设置这个颜色。就像这样:

<p [myHighlight]="color">Highlight me!</p>

You can extend the directive class with a bindable input highlightColor property and use it to highlight text.

我们将给指令类增加一个可绑定输入属性highlightColor,用它来加亮文本。

Here is the final version of the class:

这里是该类的最终版:

app/highlight.directive.ts (class)

export class HighlightDirective { private _defaultColor = 'red'; constructor(private el: ElementRef, private renderer: Renderer) { } @Input('myHighlight') highlightColor: string; @HostListener('mouseenter') onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color); } }

The new highlightColor property is called an input property because data flows from the binding expression into the directive. Notice the @Input() decorator applied to the property.

新的highlightColor属性被称为输入属性,因为数据是从绑定表达式流入指令中。 注意,在定义这个属性的时候,我们调用了@Input()装饰器。

app/highlight.directive.ts (color)

@Input('myHighlight') highlightColor: string;

@Input adds metadata to the class that makes the highlightColor property available for property binding under the myHighlight alias. Without this input metadata Angular rejects the binding. See the appendix below for more information.

@Input向类添加元数据,使highlightColor属性能以myHighlight为别名进行绑定。 没有这个输入元数据,Angular 会拒绝绑定。 更多信息,见下面的附录

@Input(alias)

@Input(别名

Currently, the code aliases the highlightColor property with the attribute name by passing myHighlight into the @Input decorator:

当前,代码通过将myHighlight传递到@Input装饰器,把myHighlight属性作为highlightColor属性的别名

@Input('myHighlight') highlightColor: string;

The code binds to the attribute name, myHighlight, but the the directive property name is highlightColor. That's a disconnect.

代码绑定到myHighlight属性名,但是指令属性名为highlightColor。这是一个断点。

You can resolve the discrepancy by renaming the property to myHighlight and define it as follows:

你可以通过重命名属性名到myHighlight来移除这个区别,像这样:

@Input() myHighlight: string;

Now that you're getting the highlight color as an input, modify the onMouseEnter() method to use it instead of the hard-coded color name and define red as the default color.

现在,通过输入型属性得到了高亮的颜色,然后修改onMouseEnter()来使用它代替硬编码的那个颜色名, 并将红色定义为默认颜色。

@HostListener('mouseenter') onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }

To let users pick the highlight color and bind their choice to the directive, update app.component.html as follows:

更新AppComponent的模板,来让用户选择一个高亮颜色,并把选择结果绑定到指令上:

<h1>My First Attribute Directive</h1> <h4>Pick a highlight color</h4> <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 [myHighlight]="color">Highlight me!</p>

Where is the templated color property?

模板的 color 属性在哪里?

You may notice that the radio button click handlers in the template set a color property and the code is binding that color to the directive. However, you never defined a color property for the host AppComponent. Yet this code works. Where is the template color value going?

你可能注意到,模板中的单选按钮的点击事件处理器设置了一个color属性,而且把color绑定到指令上。 但是,你从未在这个宿主AppComponent中定义color属性,代码仍然工作正常。模板的color值去哪儿了?

Browser debugging reveals that Angular dynamically added a color property to the runtime instance of the AppComponent.

在浏览器中调试就会发现,Angular 在AppComponent的运行期实例上添加了一个color属性。

This is convenient behavior but it is also implicit behavior that could be confusing. For clarity, consider adding the color property to the AppComponent.

这是一个很便利的行为,但它也是隐式的行为,这容易让人困惑。 虽然这样也可行,但我们建议你还是要把color属性加到AppComponent中。

Here is the second version of the directive in action.

下面是指令操作演示的第二版。

Highlight v.2

Bind to a second property

绑定到第二个属性

This example directive only has a single customizable property. A real app often needs more.

本例的指令只有一个可定制属性,真实的引用通常需要更多。

Let's allow the template developer to set the default color—the color that prevails until the user picks a highlight color. To do this, first add a second input property to HighlightDirective called defaultColor:

要让模板开发者设置一个默认颜色,直到用户选择了一个高亮颜色才失效。 给HighlightDirective添加第二个输入型属性defaultColor

@Input() set defaultColor(colorName: string){ this._defaultColor = colorName || this._defaultColor; }

The defaultColor property has a setter that overrides the hard-coded default color, "red". You don't need a getter.

defaultColor属性是一个 setter 函数,它代替了硬编码的默认颜色 “red”。不需要 getter 函数。

How do you bind to it? The app is already using myHighlight attribute name as a binding target.

该如何绑定到它?别忘了已经把myHighlight属性名用作绑定目标了。

Remember that a component is a directive, too. You can add as many component property bindings as you need by stringing them along in the template as in this example that sets the a, b, c properties to the string literals 'a', 'b', and 'c'.

记住,组件也是指令。 只要需要,就可以通过把它们依次串在模板中来为组件添加多个属性绑定。 下面这个例子中就把abc属性设置为了字符串字面量'a'、'b'、'c'。

<my-component [a]="'a'" [b]="'b'" [c]="'c'"><my-component>

The same holds true for an attribute directive.

在属性型指令中也可以这样做。

<p [myHighlight]="color" [defaultColor]="'violet'"> Highlight me too! </p>

Here the code is binding the user's color choice to the myHighlight attribute as before. It is also binding the literal string, 'violet', to the defaultColor.

这里,我们像以前一样把用户选择的颜色绑定到了myHighlight上。 我们把字符串字面量'violet'绑定到了defaultColor上。

Here is the final version of the directive in action.

下面就是该指令最终版的操作演示。

Final Highlight

Summary

总结

This page covered how to:

本章介绍了如何:

The final source:

最终的源码如下:

import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'my-app', templateUrl: 'app.component.html' }) export class AppComponent { } <h1>My First Attribute Directive</h1> <h4>Pick a highlight color</h4> <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 [myHighlight]="color">Highlight me!</p> <p [myHighlight]="color" [defaultColor]="'violet'"> Highlight me too! </p> import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { private _defaultColor = 'red'; constructor(private el: ElementRef, private renderer: Renderer) { } @Input() set defaultColor(colorName: string){ this._defaultColor = colorName || this._defaultColor; } @Input('myHighlight') highlightColor: string; @HostListener('mouseenter') onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color); } } import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HighlightDirective } from './highlight.directive'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, HighlightDirective ], bootstrap: [ AppComponent ] }) export class AppModule { } import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Attribute Directives</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="styles.css"> <!-- Polyfills for older browsers --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <script src="systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <body> <my-app>loading...</my-app> </body> </html>

Appendix: Input properties

附录:输入属性

In this demo, the highlightColor property is an input property of HighlightDirective.

本例中, highlightColor属性是HighlightDirective指令的一个输入属性。

You've seen properties in bindings before but never had to declare them as anything. Why now?

以前也见过属性绑定,但我们从没有定义过它们。为什么现在就不行了?

Angular makes a subtle but important distinction between binding sources and targets.

Angular 在绑定的目标之间有一个巧妙但重要的区别。

In all previous bindings, the directive or component property was a binding source. A property is a source if it appears in the template expression to the right of the equals (=).

在以前的所有绑定中,指令或组件的属性都是绑定。 如果属性出现在了模板表达式等号 (=) 的右侧,它就是一个

A property is a target when it appears in square brackets ([ ]) to the left of the equals (=) as it is does when binding to the myHighlight property of the HighlightDirective.

如果它出现在了方括号 ([ ]) 中,并且出现在等号 (=) 的左侧,它就是一个目标, 就像在绑定到HighlightDirectivemyHighlight属性时所做的那样。

<p [myHighlight]="color">Highlight me!</p>

The 'color' in [myHighlight]="color" is a binding source. A source property doesn't require a declaration.

[myHighlight]="color"中的 'color' 是绑定。 源属性不需要声明。

The 'myHighlight' in [myHighlight]="color" is a binding target. You must declare it as an input property or Angular rejects the binding with a clear error.

[myHighlight]="color"中的 'myHighlight' 是绑定目标。 必须把它定义为一个输入属性,否则,Angular 就会拒绝绑定,并给出一个明确的错误。

Angular treats a target property differently for a good reason. A component or directive in target position needs protection.

Angular 这样区别对待目标属性有充分的理由。 作为目标的组件或指令需要保护。

Imagine that HighlightDirective did truly wonderous things in a popular open source project.

假想一下,在一个开源项目中,HighlightDirective做了些很精彩的事。

Surprisingly, some people — perhaps naively — start binding to every property of the directive. Not just the one or two properties you expected them to target. Every property. That could really mess up your directive in ways you didn't anticipate and have no desire to support.

出乎意料的是,有些人(可能因为太天真)开始绑定到这个指令中的每一个属性。 不仅仅只是我们预期为绑定目标的那一两个属性,而是每一个。 这可能会扰乱指令的工作方式 —— 我们既不想这样做也不想支持它们这样做。

The input declaration ensures that consumers of your directive can only bind to the properties of the public API but nothing else.

于是,这种输入声明可以确保指令的消费者只能绑定到公开 API 中的属性,其它的都不行。