Posted on Leave a comment

[功能介紹-6] Attribute Directives

Directive有分為結構型和屬性型的,這一篇要先介紹屬性型的Directive。
本篇的範例請見:Attribute Directive example / download example

Angular有三種directive:

  • 元件 – 包含template的directive。
  • 結構指令 – 通過添加和刪除DOM元素來更改DOM佈局。(如ngFor、ngIf)
  • 屬性指令 – 改變元素,組件或其他指令的外觀或行為。(如ngStyle)

建立一個簡單的屬性型directive

一個directive最少需要一個帶有@Directive宣告的檔案,告訴angular該如何識別這個directive。
這邊會用一個high light的directive範例來解說,當用戶將鼠標懸停在該元素上時,設置元素的背景色。你可以像這樣應用它:

<p appHighlight>Highlight me!</p>

而下面會一步步創立這一個directive。

首先,用cli創立一個新的directive

ng generate directive highlight

會看到cli自動建立了兩個新的檔案

產生的src/app/highlight.directive.ts檔案的內容如下:

import { Directive } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor() { }
}

當我們import了Directive後,就可以在檔案內使用@Directive來設定directive的CSS attribute selector
方括弧[]可以讓它成為一個屬性選擇器,在這邊為什麼會取為appHighlight而不是highlight,是為了避免與現有的html指令衝突,建議最好在所有的directive前面加上前綴字,以方便識別這是那邊來的屬性。如果沒有前綴字,很容易會發生難以識別的錯誤

接著看src/app/highlight.directive.ts的內容:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

這邊可以看到在建構子的地方會傳入ElementRef,並且使用el.nativeElement直接修改DOM元素的背景顏色。

若希望directive能夠接收使用者事件,可以加載HostListener,如下:

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;
  }

顯示的結果如下圖:

當然,也可以通過標準的JavaScript來訪問DOM,並手動添加事件監聽器。這種方法至少有三個問題,是不被建議的:

  • 需正確的堅聽到各種平台的事件
  • 當要destroy這個directive時要手動移除事件
  • 直接操作DOM API不是好的方式

輸入參數至directive

首先要先import所需的Input

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

然後宣告所要輸入的變數

@Input() highlightColor: string;

那麼在使用directivet傳入參數的方式有下面幾種

<p appHighlight highlightColor="yellow">Highlighted in yellow</p>
<p appHighlight &#91;highlightColor&#93;="'orange'">Highlighted in orange</p>
<p &#91;appHighlight&#93;="'orange'">Highlight me!</p>

下面這個範例是使用上面自製的directive,讓使用者選擇highlight的顏色
template檔案內容如下:

<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 &#91;appHighlight&#93;="color">Highlight me!</p>

component內容如下:

export class AppComponent {
  color: string;
}

最後結果如下圖:

Leave a Reply