Skip to content

Instantly share code, notes, and snippets.

@joergpatz
Last active March 14, 2017 18:01
Show Gist options
  • Save joergpatz/12fefffa56db30ae2535ba33e08af7db to your computer and use it in GitHub Desktop.
Save joergpatz/12fefffa56db30ae2535ba33e08af7db to your computer and use it in GitHub Desktop.
ng2-focus-forward-directive
import { Directive, HostListener, ElementRef, Renderer } from '@angular/core';
@Directive({
selector: 'input'
})
export class InputFocusForwarderDirective {
constructor(private elRef: ElementRef, private renderer: Renderer) {
}
@HostListener('focus') onFocus() {
this.renderer.invokeElementMethod(this.elRef.nativeElement,
'dispatchEvent',
[new CustomEvent('input-focus', {bubbles: true})]);
// or just
// el.dispatchEvent(new CustomEvent('input-focus', { bubbles: true }));
// if you don't care about webworker compatibility
}
@HostListener('focusout') onFocusOut() {
this.renderer.invokeElementMethod(this.elRef.nativeElement,
'dispatchEvent',
[new CustomEvent('input-focus-out', {bubbles: true})]);
// or just
// el.dispatchEvent(new CustomEvent('input-focus', { bubbles: true }));
// if you don't care about webworker compatibility
}
}
@joergpatz
Copy link
Author

@Component({
  selector: 'my-component',
  template: `
<form>
  <input type="text">
</form>`
}) {
  @HostListener('input-focus', ['$event.target']) onInputFocus(target) {
    console.log('FOCUS', target);
  }

  @HostListener('input-focus-out', ['$event.target']) onInputFocusOut(target) {
    console.log('FOCUSOUT', target);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment