可以通过创建一个Angular指令来对主机输出做出反应。下面是一个示例代码:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHostListener]'
})
export class HostListenerDirective {
constructor(private el: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
在这个示例中,我们创建了一个名为HostListenerDirective
的指令。通过使用@Directive
装饰器,我们定义了该指令的选择器为[appHostListener]
。
在构造函数中,我们注入了ElementRef
,它允许我们访问指令所在的DOM元素。
我们使用@HostListener
装饰器来监听主机元素上的事件。在这个例子中,我们监听了mouseenter
和mouseleave
事件。
当鼠标进入主机元素时,onMouseEnter
方法会被调用,我们调用highlight
方法将主机元素的背景颜色设置为黄色。
当鼠标离开主机元素时,onMouseLeave
方法会被调用,我们调用highlight
方法将主机元素的背景颜色恢复为默认值。
最后,highlight
方法接收一个颜色参数,根据传入的颜色值设置主机元素的背景颜色。
要使用这个指令,只需将其添加到想要应用它的元素上,如下所示:
Hover over me
这样,当鼠标悬停在这个相关内容