@HostBinding()和@HostListener()在自定義指令時非常有用。@HostBinding()可以為指令的宿主元素添加類、樣式、屬性等,而@HostListener()可以監聽宿主元素上的事件。
@HostBinding()和@HostListener()不僅僅用在自定義指令,只是在自定義指令中用的較多
本文基於Angular2+
在介紹 HostListener 和 HostBinding 屬性裝飾器之前,我們先來了解一下 host element (宿主元素)。
宿主元素的概念同時適用於指令和組件。對於指令來說,這個概念是相當簡單的。應用指令的元素,就是宿主元素。假設我們已聲明了一個 HighlightDirective 指令 (selector: '[exeHighlight]'):
-
<p exeHighlight>
-
<span>高亮的文本</span>
-
</p>
上面 html 代碼中,p 元素就是宿主元素。如果該指令應用於自定義組件中如:
-
<exe-counter exeHighlight>
-
<span>高亮的文本</span>
-
</exe-counter>
此時 exe-counter 自定義元素,就是宿主元素。
HostListener 是屬性裝飾器,用來為宿主元素添加事件監聽。
下面我們通過實現一個在輸入時實時改變字體和邊框顏色的指令,學習@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()監聽宿主元素的keydown事件,為color和borderColor隨機分配顏色
OK,現在就來使用我們的指令:
<input appRainbow>
效果就像這樣:
轉自:https://www.cnblogs.com/cme-kai/p/8352087.html
