1. 程式人生 > 實用技巧 >Angular如何自定義attribute指令

Angular如何自定義attribute指令

需求:
實現一個自定義的attribute directive,當施加到某個html element時,滑鼠hover上去,會修改其背景顏色。

Highlight me!

下面是具體做法。

(1) 使用命令列建立directive:

ng generate directive highlight

自動生成的檔案:


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

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

  constructor() { }

}

中括號語法標註了這是一個attribute指令。Angular在處理模板裡的html元素時,如果發現某個元素具有appHighlight屬性,就會將該指令的行為施加給該元素。

這裡的selector之所以不取名為highlight,是為了避免和html標準的屬性衝突。同樣,不使用ng作為字首,為了避免和Angular預置的attribute指令衝突。使用app代表這是應用開發人員自定義的attribute指令。

指令的具體實現放在highlight.directive.ts裡:

通過建構函式引數注入方式,將被施加attribute指令的DOM元素注入,這樣指令可以通過nativeElement操作該DOM元素。

(2) 在html裡消費該指令:

最後的效果:

It created an instance of the HighlightDirective class and injected a reference to the

element into the directive's constructor which sets the

element's background style to yellow.

在執行時,Angular找到模板裡標註了appHighlight指令的element後,建立一個HighlightDirective class的例項,將這個element注入到directive例項的建構函式裡。

要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":