假設有這樣一個需求:咱們須要加強 HTML 裏原生的 input 標籤,讓其達到,隨着用戶輸入字符時,其顏色自動切換的效果。git
這是一個典型的能夠使用 Angular Directive 實現的需求。github
每一個 Directive 都有一個 host 元素。spring
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 元素的屬性自己。typescript
同理,經過 @HostListener 修飾的事件處理函數,在 host 元素髮生對應的事件以後,會自動被觸發。app
Rainbow 指令完整的實現代碼:dom
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 字體顏色自動改變。字體
完整代碼參考個人Githubthis
更多Jerry的原創文章,盡在:"汪子熙":spa