## 创建一个属性型指令 属性型指令至少需要一个带有`@[Directive]`装饰器的控制器类。该装饰器指定了一个用于标识属性的选择器。 控制器类实现了指令需要的指令行为。 ### 一、创建指令类 >[info] 在CLI输入命令:ng g directive highlight (指令类名) 输入命令后创建的指令类 `src/app/highlight.directive.ts` ``` import { Directive } from '@angular/core'; @Directive({ selector: '[appHighlight]' //属性指令的名称,使用前缀避免与内部指令冲突 }) export class HighlightDirective { constructor() { } } ``` ### 二、引入`ElementRef`模块操作DOM元素 ``` import { Directive,ElementRef } from '@angular/core'; //引入ElementReft模块操作DOM @Directive({ selector: '[appHighlight]' //属性指令的名称,使用前缀避免与内部指令冲突 }) export class HighlightDirective { //修改元素的背景颜色 constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } } ``` ### 三、引入 `HostListener`装饰器响应指令所在元素的事件 ``` import { Directive,ElementRef ,HostListener} from '@angular/core'; //引入HostListener响应指令的事件 @Directive({ selector: '[appHighlight]' //属性指令的名称,使用前缀避免与内部指令冲突 }) export class HighlightDirective { //绑定事件,响应指令的行为 //鼠标移入事件 @HostListener('mouseenter') onMouseEnter() { this.highlight('yellow'); } //鼠标移出事件 @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } //修改元素的背景颜色 private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } } ``` ### 四、使用`Input`数据绑定向指令传递值 ``` import { Directive,ElementRef ,HostListener,Input} from '@angular/core'; //引入Input模块 用于外部向指令传值 @Directive({ selector: '[appHighlight]' //属性指令的名称,使用前缀避免与内部指令冲突 }) export class HighlightDirective { //定义外部传递给指令的属性 //使用别名,外部使用appHighlight传递值,内部使用highlightColor代表值 @Input('appHighlight') highlightColor: string; @Input() defaultColor: string; //第二个属性,传递的默认值 constructor(private el: ElementRef) {} //绑定事件,响应指令行为 //鼠标移入事件 @HostListener('mouseenter') onMouseEnter() { //赋予默认值,当用户没有传递值时使用默认值 this.highlightColor = (this.highlightColor||this.defaultColor || '#673ab7'); this.highlight(this.highlightColor); } //鼠标移出事件 @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } } ``` ### 五、使用自定义指令 ``` //传递第二个参数,defaultColor="violet" <p [appHighlight]='color' defaultColor="violet">DIV指令</p> //没有传值,使用默认值 <p [appHighlight]="color" class="hello">Highlight me!</p> export class AppComponent { color: string; } ```