15

I'm trying to catch a focus event by @HostListener. But it doesn't work well for me.

I saw an article below.

HTML5 event handling(onfocus and onfocusout) using angular 2

Also saw a plunker appeared on the article.

http://plnkr.co/edit/0K1nxX2ltZ4ztfe5uJ6E?p=preview

It worked on me. However I changed it as below, it wouldn't work then.

@Component({
    selector: 'my-app',
    template: `<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">` 
})
export class App {
    @HostListener('focus', ['$event.target'])
    onFocus(target: any) 
        console.log("Focus called from HostListener");
        target.type = 'date';
    }
    @HostListener('focusout', ['$event.target'])
    onFocusout(target: any) {
        console.log("Focus out called from HostListener");
        target.type = 'text';
    }

    focusOutFunction(){
        console.log("Focus out called");
    }
    focusFunction(){
        console.log("Focus called");
    }
}

Regarding focusout, both of them are called. But focus (focusin) works only focusFunction, not work onFocus by @HostListener.

How can I make @HostListener works with focus event?

Wouter Lievens
  • 4,019
  • 5
  • 41
  • 66
Yusuke Masuda
  • 485
  • 1
  • 6
  • 19

3 Answers3

12

That's because @HostListener attaches a listener to the host element. In this case your host element is the <my-app></my-app> element. When you focus inside the <input> element the focus event does not bubble up to its parent. Also, only certain elements can actually fire a focus event and the my-app element is not one of them.

The example you posted uses a @Directive which they place on the <input> element. Which obviously makes it possible to listen for focus events on the directive.

You can however have a custom element fire a (focus) event by setting the tabindex="0" as attribute.

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
3

use blur instead of focusout HostListener

@HostListener('blur') onblur() { ....... ....... }

Rinold
  • 343
  • 1
  • 2
  • 12
1

For those desperately checking for errors in their code and finding none.

Mind that focus events are dispatched on block elements with tabindex set to something. This relates to both, (event) listeners in templates and in components via @HostListener().

pop
  • 3,464
  • 3
  • 26
  • 43