屬性型指令用於改變一個 DOM 元素的外觀或行為。
在 Angular 中有三種類型的指令:
-
組件 — 擁有模板的指令
-
結構型指令 — 通過添加和移除 DOM 元素改變 DOM 布局的指令
-
屬性型指令 — 改變元素、組件或其它指令的外觀和行為的指令。
在cmd的命令窗口里面執行命令:ng generate directive highlight
生成的 src/app/highlight.directive.ts 文件如下:
import { Directive } from '@angular/core';
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor() { }
}
import 語句還從 Angular 的 core 庫中導入了一個 ElementRef 符號。
你可以在指令的構造函數中注入 ElementRef,來引用宿主 DOM 元素,
ElementRef 通過其 nativeElement 屬性給你了直接訪問宿主 DOM 元素的能力。
使用方法:
<p appHighlight>Highlight me!</p>
總結:Angular 在宿主元素 <p> 上發現了一個 appHighlight 屬性。 然后它創建了一個 HighlightDirective 類的實例,並把所在元素的引用注入到了指令的構造函數中。 在構造函數中,該指令把 <p> 元素的背景設置為了黃色。
響應用戶引發的事件
先把 HostListener 加進導入列表中。
import { Directive, ElementRef, HostListener } from '@angular/core';
然后使用 HostListener 裝飾器添加兩個事件處理器,它們會在鼠標進入或離開時進行響應。
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
src/app/highlight.directive.ts 文件如下:
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;
}
Ps:這個demo的小例子是按照官網來的,是一個很經典的教程,為了偷懶,所以直接復制過來了。希望老司機們不要噴。謝謝
但是這樣寫的話太死板了,不夠靈活。。。比如說:我想鼠標經過不同的div元素的時候,實現不同的背景顏色,那這個時候就要用到數據綁定向指令傳值了(@Input);
直接把最終的代碼貼上來吧(運行下面的代碼可以試試)
src/app/highlight.directive.ts 文件如下:
import {Directive, ElementRef, HostListener, Input} from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
}
@Input() appHighlight: string;
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.appHighlight || 'red');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
使用的方法是:
<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 [appHighlight]="color">Highlight me!</p>
