简体   繁体   English

如何直接在模板中获取组件的元素引用?

[英]How can I get the element ref of a component directly in the template?

I have certain elements that I set focus to using mouseover as so:我将某些元素设置为使用鼠标悬停,如下所示:

<div #divTemplateVar (mouseover)="divTemplateVar.focus()"></div>

Although this doesn't seem to work for a component:虽然这似乎不适用于组件:

<component #componentTemplateVar (mouseover)="componentTemplateVar.focus()"></component>

I know I can use a我知道我可以使用

viewChild('componentTemplateVar', { read: ElementRef }) 

to select the component in the template, but I have many components that need to just focus themselves on mouseover and don't want to manually write a view child and match their id with the a mouseover function.选择模板中的组件,但我有很多组件只需要专注于鼠标悬停,不想手动编写视图子项并将它们的 id 与鼠标悬停功能匹配。

How can I get component children to auto focus themselves on the mouseover event?如何让组件子级自动将注意力集中在鼠标悬停事件上?

Make a directive : stackblitz制定指令: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM