在 Angular 指令中使用 CSS 悬停 属性?

Using CSS hover property in Angular directive?

这里是指令,默认的

import { Directive, Input, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: '[newBox]'
})
export class BoxDirective {

  @Input() backgroundColor = '#fff';
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnInit(): void {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', this.backgroundColor);
  }

}

现在,我希望在鼠标悬停时更改背景色。我如何在指令中执行此操作?

使用HostListener监听事件

  @HostListener('mouseover')
  onMouseOver() {
    this.backgroundColor = '#fff';
  }

  @HostListener('mouseout')
  onMouseOut() {
    this.backgroundColor =  '#000';
  }
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appHover]'
})
export class HoverDirective implements OnInit {
  @HostListener('mouseenter') onMouseEnter(){
    this.renderer2.setStyle(this.elRef.nativeElement,'fontSize','100px')
    this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
    this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
  }
@Input('appHover') case:string='';
  @HostListener('mouseout') onMouseOut(){
    this.renderer2.setStyle(this.elRef.nativeElement,'fontSize',this.case)
    this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
    this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
  }

  constructor(private elRef:ElementRef,private renderer2:Renderer2) { }
  ngOnInit(): void {
  
  }
  
}


转到app.component.html


then use directive.