日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2023/12/19 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 利用 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 实现输入文本框随着键盘输入自动变色效果的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。