zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

Angular输入自动 实现 利用 效果 文本框 directive
2023-09-14 09:04:00 时间

假设有这样一个需求:我们需要增强 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的原创文章,尽在:“汪子熙”: