簡(jiǎn)介
@HostBinding
和 @HostListener
是 Angular 中兩個(gè)在自定義指令中非常有用的裝飾器。@HostBinding
允許你在承載指令的元素或組件上設(shè)置屬性,而 @HostListener
則允許你監(jiān)聽(tīng)宿主元素或組件上的事件。
在本文中,你將會(huì)在一個(gè)示例指令中使用 @HostBinding
和 @HostListener
來(lái)監(jiān)聽(tīng)宿主上的 keydown
事件。
!輸入文本后,動(dòng)畫(huà)顯示每個(gè)字符更改顏色。消息拼寫(xiě)出:一種彩虹般的顏色。
它將把文本和邊框顏色設(shè)置為一組可用顏色中的隨機(jī)顏色。
先決條件
要完成本教程,你需要:
- 在本地安裝 Node.js,你可以按照《如何安裝 Node.js 并創(chuàng)建本地開(kāi)發(fā)環(huán)境》進(jìn)行操作。
- 對(duì)設(shè)置 Angular 項(xiàng)目和使用 Angular 組件有一定的了解可能會(huì)有所幫助。
本教程已經(jīng)在 Node v16.4.2、npm
v7.18.1、angular
v12.1.1 下驗(yàn)證通過(guò)。
使用 @HostBinding 和 @HostListener
首先,創(chuàng)建一個(gè)新的 RainbowDirective
。
可以通過(guò) @angular/cli
完成:
ng generate directive rainbow --skip-tests
這將把新組件添加到應(yīng)用程序的 declarations
中,并生成一個(gè) rainbow.directive.ts
文件:
import { Directive } from '@angular/core';
@Directive({
selector: '[appRainbow]'
})
export class RainbowDirective {
constructor() { }
}
添加 @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.border-color') borderColor!: string;
@HostListener('keydown') newColor() {
const colorPick = Math.floor(Math.random() * this.possibleColors.length);
this.color = this.borderColor = this.possibleColors[colorPick];
}
}
然后可以在元素上使用該指令:
<input type="text" appRainbow />
我們的 Rainbow
指令使用了兩個(gè) @HostBinding
裝飾器來(lái)定義兩個(gè)類(lèi)成員,一個(gè)綁定到宿主的 style.color
,另一個(gè)綁定到 style.border-color
。
你還可以綁定到宿主的任何類(lèi)、屬性或?qū)傩浴?/p>
以下是一些可能綁定的更多示例:
@HostBinding('class.active')
@HostBinding('disabled')
@HostBinding('attr.role')
帶有 'keydown'
參數(shù)的 @HostListener
監(jiān)聽(tīng)宿主上的 keydown 事件。我們定義了一個(gè)附加到該裝飾器的函數(shù),該函數(shù)改變了 color
和 borderColor
的值,我們的更改會(huì)自動(dòng)反映在宿主上。
結(jié)論
在本文中,你使用了 @HostBinding
和 @HostListener
在一個(gè)示例指令中監(jiān)聽(tīng)宿主上的 keydown
事件。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-834583.html
如果你想了解更多關(guān)于 Angular 的內(nèi)容,請(qǐng)查看我們的 Angular 主題頁(yè)面,了解練習(xí)和編程項(xiàng)目。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-834583.html
到了這里,關(guān)于如何在自定義 Angular 指令中使用 @HostBinding 和 @HostListener的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!