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

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

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

这是一个典型的可以使用 Angular Directive 实现的需求。

每个 Directive 都有一个 host 元素。

image.png

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

image.png

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];
  }
}

image.png

相关文章
|
2月前
Angular启动/node_modules/@types/node/index.d.ts (20,1): Invalid ‘reference‘ directive syntax.
Angular启动/node_modules/@types/node/index.d.ts (20,1): Invalid ‘reference‘ directive syntax.
44 2
|
9月前
|
JavaScript
关于 Angular 的 HostBinding 装饰器
关于 Angular 的 HostBinding 装饰器
|
10月前
从 Angular Component 和 Directive 的实例化,谈谈 Angular forRoot 方法的命令由来
同 Angular service 的单例特性不同,Angular 组件和指令通常会被多次实例化,比如 HTML markup 中每出现一次 Component 的 selector,就会触发 Component 的一次实例化。
|
11月前
|
JavaScript
Angular1.x的自定义指令directive参数配置详细说明
Angular1.x的自定义指令directive参数配置详细说明
关于调用 Angular 属性指令 attribute Directive 是否需要带中括号的问题
关于调用 Angular 属性指令 attribute Directive 是否需要带中括号的问题
138 0
关于调用 Angular 属性指令 attribute Directive 是否需要带中括号的问题
一个关于Angular Directive selector里的中括号使用问题
一个关于Angular Directive selector里的中括号使用问题
一个关于Angular Directive selector里的中括号使用问题
|
JavaScript
关于Angular directive使用的语法问题
前者用于控制或者改变 DOM,后者控制已有 elements 的外观或者行为。
关于Angular directive使用的语法问题
Angular jasmine fixture.detectChanges如何触发directive的set方法
Angular jasmine fixture.detectChanges如何触发directive的set方法
92 0
Angular jasmine fixture.detectChanges如何触发directive的set方法
每个施加在HTML元素上的Angular Directive,运行时都会生成一个新的实例
每个施加在HTML元素上的Angular Directive,运行时都会生成一个新的实例
88 0
每个施加在HTML元素上的Angular Directive,运行时都会生成一个新的实例
|
前端开发 JavaScript
Angular @Hostbinding工作原理
Angular @Hostbinding工作原理
192 0
Angular @Hostbinding工作原理