• 需求:为元素设置默认背景颜色,鼠标移入时的背景颜色以及移出时的背景颜色

    创建自定义指令

    1. ng g d directive/hover
    ```typescript import { AfterViewInit, Directive, ElementRef, HostListener, Input } from ‘@angular/core’;

// 接收参的数类型 interface Options { bgColor?: string }

@Directive({ selector: ‘[appHover]’ })

export class HoverDirective implements AfterViewInit { // 接收参数 @Input(“appHover”) appHover: Options = {}

  1. // 要操作的 DOM 节点
  2. element: HTMLElement
  3. // 获取要操作的 DOM 节点
  4. constructor(private elementRef: ElementRef) {
  5. this.element = this.elementRef.nativeElement
  6. }
  7. // 组件模板初始完成后设置元素的背景颜色
  8. ngAfterViewInit(): void {
  9. this.element.style.backgroundColor = this.appHover.bgColor || "skyblue"
  10. }
  11. // 为元素添加鼠标移入事件
  12. @HostListener("mouseenter") enter() {
  13. this.element.style.backgroundColor = "pink"
  14. }
  15. // 为元素添加鼠标移出事件
  16. @HostListener("mouseleave") leave() {
  17. this.element.style.backgroundColor = "skyblue"
  18. }

}

  1. <a name="JEgkF"></a>
  2. ### 使用自定义指令
  3. ```typescript
  4. // 不需要加[],只有在绑定动态数据的时候才加[]
  5. <div appHover></div>
  6. // 传递自定义的颜色
  7. <div [appHover]="{ bgColor: 'blue' }">Hello Angular</div>