ng2自定義指令 directive

一、自定義指令html

/*
 * Directive: 指令模塊
 * ElementRef: 獲取節點
 * Input: 獲取輸入內容
 * Renderer: 渲染新節點
 * HostListener: 這是監聽事件的, 綁定時間
 *
 * 注意:
 * 1. 指令的名稱要使用中括號括起來
 * 2. html中使用的時候, 不須要中括號
 * 3. 構造模板中傳遞參數的時候, 若是是字符串, 那麼要單引號: [myHighlight]="'blue'"
 */
import {Directive, ElementRef, HostListener, Input, Renderer} from '@angular/core';
@Directive({
  selector: '[myHighlight]'
})
export class OneDirective {
  constructor(private el:ElementRef, private renderer:Renderer) {

  }

  // 給myHighlight指令定義一個輸入變量(外部調取這個指令傳遞的參數)
  @Input("myHighlight") chColor: string;

  @HostListener("click") onClick() {
    // 調用函數, 傳遞指令外部獲取的顏色
    this.changeColor(this.chColor);
  }
  // 自定義函數
  public changeColor(color: string) {
    this.renderer.setElementStyle(this.el.nativeElement, "background-color", color);
  }
}

二、app.module.ts主模塊中引入指令app

import {HighLight} from "../directive/high-light.directive.ts"
@ngModule({
    declarations: [
        HighLight
    ]
})

三、模板中使用指令函數

<p myHighlight="yellow">
    自定義指令
</p>
相關文章
相關標籤/搜索