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 field:
<input appRainbow/>
在directive实现内部,通过@HostBinding达到directive施加的host元素的css样式和directive属性绑定的目的。
directive施加的host元素一旦发生keydown事件,会自动触发directive实现的onKeydown函数,每触发一次,修改color和borderColor属性的值,达到host元素变色的效果: