- 需求:为元素设置默认背景颜色,鼠标移入时的背景颜色以及移出时的背景颜色
创建自定义指令
```typescript import { AfterViewInit, Directive, ElementRef, HostListener, Input } from ‘@angular/core’;ng g d directive/hover
// 接收参的数类型 interface Options { bgColor?: string }
@Directive({ selector: ‘[appHover]’ })
export class HoverDirective implements AfterViewInit { // 接收参数 @Input(“appHover”) appHover: Options = {}
// 要操作的 DOM 节点element: HTMLElement// 获取要操作的 DOM 节点constructor(private elementRef: ElementRef) {this.element = this.elementRef.nativeElement}// 组件模板初始完成后设置元素的背景颜色ngAfterViewInit(): void {this.element.style.backgroundColor = this.appHover.bgColor || "skyblue"}// 为元素添加鼠标移入事件@HostListener("mouseenter") enter() {this.element.style.backgroundColor = "pink"}// 为元素添加鼠标移出事件@HostListener("mouseleave") leave() {this.element.style.backgroundColor = "skyblue"}
}
<a name="JEgkF"></a>### 使用自定义指令```typescript// 不需要加[],只有在绑定动态数据的时候才加[]<div appHover></div>// 传递自定义的颜色<div [appHover]="{ bgColor: 'blue' }">Hello Angular</div>
