天天看點

Angular6在自定義指令中使用@HostBingDing() 和@HostListener()

emmm,,,最近在為項目的第二階段鋪路,偶然看到directive,想想看因為項目已經高度內建了第三方元件,是以對于自定義指令方面的經驗自己實在知之甚少,後面經過閱讀相關資料,總結一篇關于在自定義指令中使用@HostBingDing() 和@HostListenner()。

在使用這兩個屬性之前,必須明白一件事,就是在angular中有三種directive:

Angular6在自定義指令中使用@HostBingDing() 和@HostListener()

如圖所示,component與其他兩個directive的一個很明顯的差別就是component有template

宿主(host)

下面提到的一個宿主術語,在angular中宿主可以是component也可以是element

@HostBinding() 裝飾器

設定宿主的屬性,比如樣式: height,width,color,margin, border等等

用法: @HostBingding()接受一個參數,這個參數用于指定宿主的屬性的名字

@HostBinding('class.active')

@HostBinding('disabled')

@HostBinding('attr.role')      

@HostListener() 裝飾器

處理宿主的事件,比如mouseover, mosuout, keydown等等

用法:@HostListener() 接受一個參數,該參數用于指定宿主的事件的名字

舉個例子

使用指令行生成rainbow自定指令

ng g directive rainbow      

這裡定義個自定義指令 raibow,directive.ts

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

@Directive({
  selector: '[appRainbow]'
})
export class RainbowDirective {
    possibleColors = [
        'darksalmon', 'hotpink', 'lightskyblue', 'goldenrod', 'peachpuff',
        'mediumspringgreen', 'cornflowerblue', 'blanchedalmond', 'lightslategrey'
    ];

    @HostBinding('style.color') color: string;
    // @HostBinding('style.border-color') borderColor: string;
    @HostBinding('style.border-bottom-color') borderBottomColor: string;

    @HostListener('keydown') newColor() {
        const colorPick = Math.floor(Math.random() * this.possibleColors.length);

        this.color = this.borderBottomColor = this.possibleColors[colorPick];
    }
}      

在任意宿主中使用該指令

<input type="text" appRainbow>      

最終效果:

不知道為蝦米動态圖檔上傳不了,大概就是每次輸入鍵盤input的邊框和文字的顔色會随機動态改變

作者:

承蒙時光

出處:

http://www.cnblogs.com/timetimetime/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

繼續閱讀