利用 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的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的利用 Angular Directive 和 @HostBinding 实现输入文本框随着键盘输入自动变色效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SAP Fiori 页面的周期性动态刷新
- 下一篇: 数据结构与算法(周测7-拓扑排序和AOV