Angular2 – @HostListener(‘focus’)不起作用

前端之家收集整理的这篇文章主要介绍了Angular2 – @HostListener(‘focus’)不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正试图通过@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");
    }
}

关于焦点,他们都被称为.
但焦点(focusin)仅适用于focusFunction,而不适用于@HostListener的onFocus.

如何使@HostListener与焦点事件一起使用?

解决方法

那是因为@HostListener将一个监听器附加到host元素.在这种情况下,您的主机元素是< my-app>< / my-app>元件.当您在< input>内聚焦时元素焦点事件不会冒泡到其父级.此外,只有某些元素可以实际触发焦点事件,而my-app元素不是其中之一.

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

但是,您可以通过将tabindex =“0”设置为属性来使自定义元素触发(焦点)事件.

猜你在找的Angularjs相关文章