Angular2 - @HostListener('focus')不起作用
问题描述:
我试图通过@HostListener捕获焦点事件。 但它不适合我。Angular2 - @HostListener('focus')不起作用
我在下面看到一篇文章。
HTML5 event handling(onfocus and onfocusout) using angular 2
还看见一个plunker出现在文章。
http://plnkr.co/edit/0K1nxX2ltZ4ztfe5uJ6E?p=preview
它的工作在我身上。 但是我改变它如下,它不会工作。
@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");
}
}
关于聚焦,他们都被调用。 但焦点(focusin)只能使用focusFunction,而不能通过@HostListener在onFocus上工作。
我如何使@HostListener与焦点事件一起工作?
答
这是因为@HostListener
将侦听器附加到主机元素。在这种情况下,您的主机元素是<my-app></my-app>
元素。当您关注<input>
元素时,焦点事件不会冒泡到其父项。此外,只有某些元素实际上可以触发focus
事件,并且my-app
元素不是其中之一。
您发布的示例使用@Directive
,它们放置在<input>
元素上。这显然可以监听指令上的焦点事件。
但是,通过将tabindex="0"
设置为属性,您可以通过自定义元素触发(focus)
事件。
答
使用模糊,而不是事件的内容 HostListener
@HostListener('blur') onblur() { ....... ....... }
谢谢你的回复。我知道了。我误解了主持人的角色。 –