1. 創(chuàng)建指令文件
ng generate directive highlight
2.在highlight.directive.ts 中加入自定義樣式(使用?HostListener?裝飾器添加兩個(gè)事件處理器,它們會(huì)在鼠標(biāo)進(jìn)入或離開(kāi)時(shí)進(jìn)行響應(yīng))
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
? selector: '[appHighlight]'
})
export class HighlightDirective {
@Input('appHighlight')??highlightColor: string;? //highlightColor是appHighlight指令的別名
? constructor(private el: ElementRef) {
? //? el.nativeElement.style.backgroundColor = 'yellow';
? }
? private highlight(color: string) {
? ? this.el.nativeElement.style.backgroundColor = color;
? }
? @HostListener('mouseenter') onMouseEnter() {
? ? this.highlight(this.highlightColor);
? }
? @HostListener('mouseleave') onMouseLeave() {
? ? this.highlight(null);
? }
}

3.在app.module.ts 中引入指令文件
import { HighlightDirective } from './highlight.directive';
declarations:[?HighlightDirective ]
4.在app.component.html 中應(yīng)用指令
<p appHighlight>Highlight me!</p>? // 直接應(yīng)用
5.運(yùn)行本應(yīng)用并確認(rèn):當(dāng)把鼠標(biāo)移到?p?上的時(shí)候,背景色就出現(xiàn)了,而移開(kāi)的時(shí)候,它消失了


使用?@Input?數(shù)據(jù)綁定向指令傳遞值
6.在app.component.ts中定義屬性
color = 'yellow';
7. 在app.component.html 中應(yīng)用指令
?<p [appHighlight]="color"?>?Highlight me!</p>??