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

awe*_*pro 2 css angular-directive angular2-directives angular

这是指令,默认的。

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

现在,在悬停时,我希望改变背景颜色。我如何在指令中做到这一点?

Sac*_*aka 5

用于HostListener监听事件

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

  @HostListener('mouseout')
  onMouseOut() {
    this.backgroundColor =  '#000';
  }
Run Code Online (Sandbox Code Playgroud)