如何在纯Typescript(无JQuery)中生成Escape键

时间:2017-09-18 12:16:07

标签: angular typescript events

我正在尝试在Angular单元测试中触发Escape按钮按下事件。

    const event = document.createEvent('UIEvent');
    event.initUIEvent('keydown', true, true, window, 0);
    (<any>event).keyCode = 27;
    (<any>event).key = 'Escape';
    (<any>event).charCode = 27;

    document.body.dispatchEvent(event);

这根本不起作用(事件永远不会被正确检查的侦听器捕获,例如event.which == 27)。

创建此类活动的正确方法是什么?

我也尝试过这个,徒劳无功

    const event = new Event('keydown', {bubbles: true});
    event.initEvent('keydown', true, true);
    (<any>event).keyCode = 27;
    (<any>event).key = 'Escape';
    (<any>event).charCode = 27;

    document.body.dispatchEvent(event);

1 个答案:

答案 0 :(得分:0)

您只需要在文档或元素上使用键盘事件

     const event = new KeyboardEvent("keydown",{
     'key': 'Escape'
     });
     document.dispatchEvent(event);

您可以使用HostListener

进行测试
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
    let keyPressed = event.keyCode;
    if (keyPressed === 27) {
       console.log('Escape!');
    }
}