@HostBinding()和@HostListener()在自定義指令時非常有用。@HostBinding()可以為指令的宿主元素添加類、樣式、屬性等,而@HostListener()可以監(jiān)聽宿主元素上的事件。
@HostBinding()和@HostListener()不僅僅用在自定義指令,只是在自定義指令中用的較多
本文基于Angular2+
下面我們通過實現(xiàn)一個在輸入時實時改變字體和邊框顏色的指令,學習@HostBinding()和@HostListener()的用法。
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.borderColor') borderColor: string;③ @HostListener('keydown') onKeydown(){④ const colorPick = Math.floor(Math.random() * this.possibleColors.length); this.color = this.borderColor = this.possibleColors[colorPick]; }}說一下上面代碼的主要部分:
①:為我們的指令取名為appRainbow
②:定義我們需要展示的所有可能的顏色
③:定義并用@HostBinding()裝飾color和borderColor,用于設置樣式
④:用@HostListener()監(jiān)聽宿主元素的keydown事件,為color和borderColor隨機分配顏色
OK,現(xiàn)在就來使用我們的指令:
<input appRainbow>
效果就像這樣:

NOTE:別忘了把指令引入你的模塊
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答