如何在自定义 Angular 指令中使用 @HostBinding 和 @HostListener

简介

@HostBinding@HostListener是角度上的两个装饰符,在定制指令中非常有用。@HostBinding允许您设置托管指令的元素或组件的属性,@HostListener允许您监听主机元素或组件上的事件。

在本文中,您将在监听主机上的keydown事件的示例指令中使用@HostBinding@HostListener

随着每个字符的颜色变化,输入到输入中的文本的动画gif。这句话的意思是:colors.的彩虹

它将从几种可用颜色中将文本和边框颜色设置为随机颜色。

前提条件

要完成本教程,您需要:

本教程使用Node v16.4.2、npmv7.18.1、angularv12.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事件。我们定义了一个附加到该修饰符的函数来更改ColorborderColor的值,我们的更改会自动反映到宿主上。

结论

在本文中,您在监听主机上的keydown事件的示例指令中使用了@HostBinding@HostListener

如果您想了解更多有关ANGLE的信息,请查看我们的ANGLE主题页面以获取练习和编程项目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus