Angular @HostBinding,和@HostListener

@HostBinding()和@HostListener()在自定义指令时非常有用。@HostBinding()可以为指令的宿主元素添加类、样式、属性等,而@HostListener()可以监听宿主元素上的事件。

@HostBinding()和@HostListener()不仅仅用在自定义指令,只是在自定义指令中用的较多

本文基于Angular2+

在介绍 HostListener 和 HostBinding 属性装饰器之前,我们先来了解一下 host element (宿主元素)。

宿主元素的概念同时适用于指令和组件。对于指令来说,这个概念是相当简单的。应用指令的元素,就是宿主元素。假设我们已声明了一个 HighlightDirective 指令 (selector: '[exeHighlight]'):

  1. <p exeHighlight>

  2. <span>高亮的文本</span>

  3. </p>

上面 html 代码中,p 元素就是宿主元素。如果该指令应用于自定义组件中如:

  1. <exe-counter exeHighlight>

  2. <span>高亮的文本</span>

  3. </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>

效果就像这样:

Angular @HostBinding,和@HostListener

转自:https://www.cnblogs.com/cme-kai/p/8352087.html