在angular2的@contentChild中检测焦点事件的最佳方法是什么? [英] What is the best way to detect focus event in @contentChild in angular2?

查看:67
本文介绍了在angular2的@contentChild中检测焦点事件的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在ng-content标签之间有一个预计的本机输入. 我知道,我可以使用@ContentChild获得对投影输入的引用. 我不知道如何检测到投影输入元素在父组件中的焦点事件?

Assumed I have a projected native input between ng-content tag. I know, I can get the reference to the projected input with @ContentChild. I wonder how I could detect e.g. the focus event of the projected input element in the parent component?

推荐答案

没有办法. focus 事件不会冒泡,因此需要直接在元素上收听.

There is no way. The focus event doesn't bubble, therefore needs to be listened to on the element directly.

如果可以使用@ContentChild()获取参考,则可以使用

If you can get the reference using @ContentChild() you can use

constructor(private renderer:Renderer) {}

someMethod() {
  this.renderer.invokeElementMethod(
    this.focusableChild.nativeElement, 
    'addEventListener', ['focus', onFocus.bind(this)]
  ); 
}

如果您控制组件的使用方式,则可以对内容应用指令,如

If you control how your component is used you could apply a directive to your content like explained in How to realize website with hundreds of pages in Angular2 that forwards focus events to bubbling events by dispatching a custom event the parent element can listen to like

@Component({
  template: `... <ng-content></ng-content>
  ...
})
class MyComponent {
  @HostBinding('custom-focus', ['$event'])
  onFocus(event) {
    ...
  }
}

这篇关于在angular2的@contentChild中检测焦点事件的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆