【发布时间】:2022-08-08 21:52:01
【问题描述】:
我正在开发一个 Angular 项目,其中指令需要对 mouseenter 和 mouseleave 事件做出反应。它需要更新使用它的宿主元素的 CSS。
考虑下面的人为示例:
import { Directive, ElementRef, HostListener } from \'@angular/core\';
@Directive({
selector: \'[appMouseEvents]\',
})
export class MouseEventsDirective {
constructor(private element: ElementRef) {
}
@HostListener(\'mouseEnter\', [\'$event\'])
onMouseEnter() {
console.log(\'mouseenter\');
}
@HostListener(\'mouseleave\',[\'$event\'])
onMouseLeave() {
console.log(\'mouseleave\');
}
}
app.component.html
<hello name=\"{{ name }}\"></hello>
<p appMouseEvents>
Hover Mouse over me
</p>
当我在 Angular 开发工具中分析应用程序时,我看到这些事件导致 Angular 触发更改检测,这是不需要的,因为只有宿主元素的 CSS 受到影响。
有没有办法对指令中的鼠标事件做出反应而不触发更改检测?
这是一个演示应用程序: https://stackblitz.com/edit/angular-ivy-r6ln5w?file=src%2Fapp%2Fapp.component.ts
-
等等为什么不使用
:hover伪类来处理这种情况?
标签: angular angular-changedetection