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


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

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

如圖所示,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的邊框和文字的顏色會隨機動態改變

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM