且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在angular2的@contentChild中检测焦点事件的***方法是什么?

更新时间:2022-06-01 01:34:03

没有办法. 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) {
    ...
  }
}