屬性型指令至少須要一個帶有 @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;
}
}