利用 Angular Directive 和 @HostBinding 实现输入文本框随着键盘输入自动变色效果

假设有这样一个需求:咱们须要加强 HTML 里原生的 input 标签,让其达到,随着用户输入字符时,其颜色自动切换的效果。git

这是一个典型的能够使用 Angular Directive 实现的需求。github

每一个 Directive 都有一个 host 元素。spring

Decorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.

Directive 里,修改 @HostBinding 修饰的 Directive 属性,就至关于修改了 DOM 元素的属性自己。typescript

同理,经过 @HostListener 修饰的事件处理函数,在 host 元素发生对应的事件以后,会自动被触发。app

Rainbow 指令完整的实现代码:dom

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);
    console.log('Jerry colorPick: ' + colorPick);
    this.color = this.borderColor = this.possibleColors[colorPick];
  }
}

消费这个指令的方法很是简单:函数

最后的效果:随着我在 input 字段里输入字段,input 字体颜色自动改变。
字体

完整代码参考个人Githubthis

更多Jerry的原创文章,尽在:"汪子熙":
spa