zoukankan      html  css  js  c++  java
  • 利用 Angular Directive 和 @HostBinding 实现输入文本框随着键盘输入自动变色效果

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

  • 相关阅读:
    例子:动能并不是特别强(2-3)后,下M5的同时,也是恢复期到期的前一天
    .NET 自带的动态代理+Expression 实现AOP
    自旋锁-SpinLock(.NET 4.0+)
    使用Nito.AsyncEx实现异步锁
    C# 两行代码实现 延迟加载的单例模式(线程安全)
    C++ 用于大型程序的工具
    C++ 模板与泛型编程
    C++ 面向对象编程
    C++ 重载操作符与转换
    C++ 复制控制
  • 原文地址:https://www.cnblogs.com/sap-jerry/p/14852739.html
Copyright © 2011-2022 走看看