[英]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.