Angular 自定义Directive里的@HostBinding和@HostListener的一个具体例子

284 阅读1分钟

Directive 的实现代码:

import {Directive, HostBinding, HostListener} from '@angular/core';

/**
 * 主要是说明@HostBinding@HostListener使用
 */
@Directive({
  selector: '[appRainbow]',
  exportAs: '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];
  }

}

消费代码:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-decorator-host',
  template: `
    <h3>@HostBinding(为宿主元素添加属性值)</h3>
    <h3>@HostListener(为宿主元素添加事件)</h3>
    <input appRainbow>
  `
})
export class DecoratorHostComponent {
}

如果directive里使用了@hostbinding来试图通过修改Directive 属性从而达到修改host元素属性的目的,那么change detection里会调用setHostBindingsByExecutingExpandoInstructions:

wrapListenerIn_markDirtyAndPreventDefault(e)

最终调用到Directive的keydown事件实现函数里:

更多Jerry的原创文章,尽在:“汪子熙”: