4

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?

westor
  • 1,426
  • 1
  • 18
  • 35
  • I deleted my answer again, sorry but i thought you work with two components. got your question wrong there. – malifa Jun 10 '16 at 10:55

1 Answers1

6

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

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) {
    ...
  }
}
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thx, Günter. It looks like an acceptable way. Would you suggest this, or wouldn´t you build components in that way (content projection of simple elements?) – westor Jun 10 '16 at 10:54
  • 1
    I would need to know more about your requirements but in general there is no strong reason why you shouldn't do that. Using the `Renderer` instead of direct access to `focusableChild.nativeElement.xxx` keeps it within the bounds of proper Angular2 way of doing stuff. – Günter Zöchbauer Jun 10 '16 at 11:27