在命令行窗口下用 CLI 命令ng generate directive
在app/directivess文件夹下创建指令类文件。
ng generate directive directives/highlight
可也一自己手动新建文件,highlight.directive.ts
app/directives/highlight.directive.ts的内容如下:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({selector: '[appHighlight]' // 指令名称})export class HighlightDirective {el:ElementRefconstructor(el: ElementRef) {this.el = el;}@Input('appHighlight') highlightColor: string; // 传进来的颜色@HostListener('mouseenter') onMouseEnter() { // 绑定事件this.highlight(this.highlightColor || 'red');}@HostListener('mouseleave') onMouseLeave() {this.highlight(null);}private highlight(color: string) {this.el.nativeElement.style.backgroundColor = color;}}
在app.module.ts中
@NgModule({declarations: [...HighlightDirective,...],...})
使用:
<p[appHighlight]="'pink'">Highlightme!</p> // 粉色
<pappHighlight>Highlightme!</p> // 红色
参考文献:angular官网-directive