假如有这样一个需要:咱们须要加强 HTML 里原生的 input 标签,让其达到,随着用户输出字符时,其色彩主动切换的成果。

这是一个典型的能够应用 Angular Directive 实现的需要。

每个 Directive 都有一个 host 元素。

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 元素的属性自身。

同理,通过 @HostListener 润饰的事件处理函数,在 host 元素产生对应的事件之后,会主动被触发。

Rainbow 指令残缺的实现代码:

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 字体色彩主动扭转。

残缺代码参考我的Github

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