[英]How can I get the element ref of a component directly in the template?
我将某些元素设置为使用鼠标悬停,如下所示:
<div #divTemplateVar (mouseover)="divTemplateVar.focus()"></div>
虽然这似乎不适用于组件:
<component #componentTemplateVar (mouseover)="componentTemplateVar.focus()"></component>
我知道我可以使用
viewChild('componentTemplateVar', { read: ElementRef })
选择模板中的组件,但我有很多组件只需要专注于鼠标悬停,不想手动编写视图子项并将它们的 id 与鼠标悬停功能匹配。
如何让组件子级自动将注意力集中在鼠标悬停事件上?
制定指令: stackblitz
export class HoverFocusDirective {
constructor(
private el: ElementRef<HTMLElement>
) { }
@HostListener('mouseover')
onMouseOver() {
this.el.nativeElement.focus();
}
@HostListener('mouseout')
onMouseOut() {
this.el.nativeElement.blur();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.