<div class="someClass" (mouseout, mouseover)="someMethod()"></div>
使用这种语法时,我会出错
ERROR DOMException: Failed to execute 'setAttribute' on 'Element': '(mouseout,' is not a valid attribute name.
但是以这种方式拆分此事件时,效果很好
<div class="someClass" (mouseout)="someMethod()" (mouseover)="someMethod()"</div>
如何在没有错误的情况下缩短语法?
答案 0 :(得分:1)
从技术上讲,您可以在mouseover
和mouseout
事件上创建带有@HostListener
的指令。
然后公开一个@Output
属性以调用您的Component函数。
类似这样的东西:
指令:
import { Directive, HostListener, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appListener]'
})
export class ListenerDirective {
@Output() appListener: EventEmitter<any> = new EventEmitter();
constructor() { }
@HostListener('mouseover')
onMouseOver(event) {
this.appListener.emit(event);
}
@HostListener('mouseout')
onMouseOut(event) {
this.appListener.emit(event);
}
}
以及您的组件模板:
<div (appListener)="someFunction($event)">
Here is some text in the DIV
</div >
以下是 Working Sample StackBlitz 供您参考。