使用命令行ng g d color:
实现源代码:
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元素变色的效果:
-1-12 星期二
经过测试,使用Directive不需要中括号:
要获取更多Jerry的原创文章,请关注公众号"汪子熙":