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?
HostListener - Declares a host listener. Angular will invoke the decorated method when the host element emits the specified event. @HostListener - will listen to the event emitted by the host element that's declared with @HostListener . HostBinding - Declares a host property binding.
Introduction. @HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.
In this article, we are going to see what is focus event in Angular 10 and how to use it. The (focus) event is triggered when an element gains its focus. Syntax: <input (focus)='functionName()'/>
HostBindinglinkDecorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.
use blur instead of focusout HostListener
@HostListener('blur') onblur() {
.......
.......
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With