Angular2 – @HostListener(‘focus’)不起作用
发布时间:2020-12-17 17:46:47 所属栏目:安全 来源:网络整理
导读:我正试图通过@HostListener捕捉焦点事件. 但它对我来说效果不佳. 我在下面看了一篇文章. HTML5 event handling(onfocus and onfocusout) using angular 2 还看到文章上出现了一个羽毛球. http://plnkr.co/edit/0K1nxX2ltZ4ztfe5uJ6E?p=preview 它对我有用.
我正试图通过@HostListener捕捉焦点事件.
但它对我来说效果不佳. 我在下面看了一篇文章. HTML5 event handling(onfocus and onfocusout) using angular 2 还看到文章上出现了一个羽毛球. 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"); } } 关于焦点,他们都被称为. 如何使@HostListener与焦点事件一起使用? 解决方法
那是因为@HostListener将一个监听器附加到host元素.在这种情况下,您的主机元素是< my-app>< / my-app>元件.当您在< input>内聚焦时元素焦点事件不会冒泡到其父级.此外,只有某些元素可以实际触发焦点事件,而my-app元素不是其中之一.
您发布的示例使用@Directive,它们放在< input>上.元件.这显然可以在指令上监听焦点事件. 但是,您可以通过将tabindex =“0”设置为属性来使自定义元素触发(焦点)事件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |