简介
@HostBinding
和@HostListener
是角度上的两个装饰符,在定制指令中非常有用。@HostBinding
允许您设置托管指令的元素或组件的属性,@HostListener
允许您监听主机元素或组件上的事件。
在本文中,您将在监听主机上的keydown
事件的示例指令中使用@HostBinding
和@HostListener
。
的彩虹
它将从几种可用颜色中将文本和边框颜色设置为随机颜色。
前提条件
要完成本教程,您需要:
- 本地安装node.js,可按照如何安装node.js并创建本地开发Environment.
- 熟悉设置角度project和使用角度components可能会有所帮助。
本教程使用Node v16.4.2、npm
v7.18.1、angular
v12.1.1进行了验证。
使用@HostBinding
和@HostListener
首先创建一个新的RainBowDirective
。
这可以通过@angular/cli
来实现:
1ng generate directive rainbow --skip-tests
这会将新组件添加到APP声明
中,并生成一个ainBow.Directive.ts
文件:
1[label src/app/rainbow.directive.ts]
2import { Directive } from '@angular/core';
3
4@Directive({
5 selector: '[appRainbow]'
6})
7export class RainbowDirective {
8
9 constructor() { }
10
11}
添加@HostBinding
和@HostListener
:
1[label src/app/rainbow.directive.ts]
2import { Directive, HostBinding, HostListener } from '@angular/core';
3
4@Directive({
5 selector: '[appRainbow]'
6})
7export class RainbowDirective {
8
9 possibleColors = [
10 'darksalmon',
11 'hotpink',
12 'lightskyblue',
13 'goldenrod',
14 'peachpuff',
15 'mediumspringgreen',
16 'cornflowerblue',
17 'blanchedalmond',
18 'lightslategrey'
19 ];
20
21 @HostBinding('style.color') color!: string;
22 @HostBinding('style.border-color') borderColor!: string;
23
24 @HostListener('keydown') newColor() {
25 const colorPick = Math.floor(Math.random() * this.possibleColors.length);
26
27 this.color = this.borderColor = this.possibleColors[colorPick];
28 }
29
30}
该指令可用于如下元素:
1[label src/app/app.component.html]
2<input type="text" appRainbow />
我们的RainBow
指令使用两个@HostBinding
修饰符来定义两个类成员,一个附加到宿主的style.Color
绑定,另一个附加到style le.edge-Color
。
您还可以绑定到宿主的任何类、属性或属性。
下面是几个可能的绑定示例:
@HostBinding(‘class.active’)
@HostBinding(‘已禁用’)
@HostBinding(‘attr.ole’)
带有‘keydown’
参数的@HostListener
监听主机上的keydown事件。我们定义了一个附加到该修饰符的函数来更改Color
和borderColor
的值,我们的更改会自动反映到宿主上。
结论
在本文中,您在监听主机上的keydown
事件的示例指令中使用了@HostBinding
和@HostListener
。
如果您想了解更多有关ANGLE的信息,请查看我们的ANGLE主题页面以获取练习和编程项目。