属性型指令至少须要一个带有 @Directive 装饰器的控制器类。该装饰器指定了一个用于标识属性的选择器。 控制器类实现了指令须要的指令行为。html
在cmd的命令窗口里面执行命令:ng generate directive highlightjson
生成的 src/app/highlight.directive.ts 文件以下:app
import { Directive } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor() { }
}
这里导入的 Directive 符号提供了 Angular 的 @Directive 装饰器。ide
@Directive 装饰器的配置属性中指定了该指令的 CSS 属性型选择器 [appHighlight]函数
这里的方括号([])表示它的属性型选择器。 Angular 会在模板中定位每一个拥有名叫 appHighlight 属性的元素,而且为这些元素加上本指令的逻辑。布局
正因如此,这类指令被称为 属性选择器 。this
在构造函数里加相关逻辑,好比,实现把宿主元素的背景色设置为黄色:spa
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
import 语句还从 Angular 的 core 库中导入了一个 ElementRef 符号。code
你能够在指令的构造函数中使用 ElementRef 来注入宿主 DOM 元素的引用,也就是你放置 appHighlight 的那个元素。htm
ElementRef 经过其 nativeElement 属性给你了直接访问宿主 DOM 元素的能力。
这里的第一个实现把宿主元素的背景色设置为了黄色。
<p appHighlight>Highlight me!</p>
总结:Angular 在宿主元素 p 上发现了一个 appHighlight 属性。 而后它建立了一个 HighlightDirective 类的实例,并把所在元素的引用注入到了指令的构造函数中。 在构造函数中,该指令把 p 元素的背景设置为了黄色。
先把 HostListener 加进导入列表中。
src/app/highlight.directive.ts (imports):
import { Directive, ElementRef, HostListener } from '@angular/core';
而后使用 HostListener 装饰器添加两个事件处理器,它们会在鼠标进入或离开时进行响应。
src/app/highlight.directive.ts (mouse-methods):
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
这个辅助方法(highlight)被从构造函数中提取了出来。 修改后的构造函数只负责声明要注入的元素 el: ElementRef。
src/app/highlight.directive.ts (constructor):
constructor(private el: ElementRef) { }
下面是修改后的指令代码:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}