angular自定義屬性指令

在angular中有三種類型的指令:
  1. 組件–擁有模板的指令;
  2. 結構性指令–經過添加和移除DOM元素改變DOM佈局的指令;
  3. 屬性型指令–改變元素、組件或其餘指令的外觀和行爲的指令;
組件是這三種指令中最經常使用的。結構性指令修改視圖的結構,例如ngfor和ngif。屬性型指令改變一個元素的外觀或行爲。

屬性型指令至少須要一個帶有 @Directive 裝飾器的控制器類。該裝飾器指定了一個用於標識屬性的選擇器。 控制器類實現了指令須要的指令行爲。html

好比定義一個名爲「highlight」的屬性型指令:

在cmd的命令窗口裏面執行命令:ng generate directive highlightjson

生成的 src/app/highlight.directive.ts 文件以下:app

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

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

這裏導入的 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';
    }
}
View Code

 

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

 

這個輔助方法(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;
  }
}
View Code
相關文章
相關標籤/搜索