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

Yus*_*uda 7 angular

我正试图通过@HostListener捕捉焦点事件.但它对我来说效果不佳.

我在下面看了一篇文章.

使用角度2的HTML5事件处理(onfocus和onfocusout)

还看到文章上出现了一个羽毛球.

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

如何@HostListener使用焦点事件进行工作?

Pie*_*Duc 7

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

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

但是,您可以(focus)通过设置tabindex="0"as属性来使用自定义元素触发事件.