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的原创文章,尽在:"汪子熙":

  • 相关阅读:
    .NET Core SignalR 和 .NET SignalR 区别
    MySQL 连接出现 Authentication plugin 'caching_sha2_password' cannot be loaded
    Geohash 基本知识及 .NET 下计算相邻8个区域编码
    ASP.NET 下配置请求大小、请求时间等参数
    .NET Core、EF、Dapper、MySQL 多种方式实现数据库操作(动态注册实体类)
    .NET Core 开发常用命令(VS Code)
    ping
    exec与xargs区别
    doc转docx
    读取docx表格中的信息
  • 原文地址:https://www.cnblogs.com/sap-jerry/p/14852739.html
Copyright © 2011-2022 走看看