gpt4 book ai didi

Angular2 - @HostListener ('focus' )不起作用

转载 作者:太空狗 更新时间:2023-10-29 17:25:13 25 4
gpt4 key购买 nike

我正在尝试通过@HostListener 捕捉焦点事件。但这对我来说效果不佳。

我在下面看到一篇文章。

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");
}
}

关于focusout,两者都调用了。但是焦点(focusin)只对focusFunction有效,对@HostListener的Focus无效。

如何让 @HostListener 与焦点事件一起工作?

最佳答案

那是因为 @HostListener将监听器附加到宿主元素。在这种情况下,您的宿主元素是 <my-app></my-app>元素。当你关注 <input> 时焦点事件不会冒泡到其父元素。此外,只有某些元素可以实际触发 focus事件和 my-app元素不是其中之一。

您发布的示例使用了 @Directive他们放在 <input> 上元素。这显然可以监听指令上的焦点事件。

但是您可以让自定义元素触发 (focus)通过设置 tabindex="0" 事件作为属性。

关于Angular2 - @HostListener ('focus' )不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com