700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 利用 Angular Directive 和 @HostBinding 实现输入文本框随着键盘输入自动变色效果

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

时间:2019-12-06 14:37:40

相关推荐

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。