angular 2 HostListener - keydown space event doesn't work in IE

时间:2017-06-15 09:59:49

标签: angular internet-explorer typescript ecmascript-6 angular2-template

I have a problem with @HostListener in IE11. I need to catch when the user uses keydown event for space, my code very simple and it works fine in Chrome and FireFox but doesn't work in IE.

import {Component, HostListener} from '@angular/core';

@Component({
  selector: 'home',
  styleUrls: ['./home.component.css'],
  templateUrl: './home.component.html'
})
export class HomeComponent {
    @HostListener('window:keydown.control.space', ['$event'])
    @HostListener('window:keydown.space', ['$event'])
    spaceEvent(event: any) {
        alert('space key!');
    }
}

In the IE developer tools, I don't see any errors or warnings, and I don't know how to resolve this problem. Any suggestion how to resolve this problem?

1 个答案:

答案 0 :(得分:3)

I found solutions. IE doesn't work correctly yet with many various events and need to use @HostListener('window:keydown', ['$event']) and then catch some keyCode

Example:

import {Component, HostListener} from '@angular/core';

@Component({
  selector: 'home',
  styleUrls: ['./home.component.css'],
  templateUrl: './home.component.html'
})
export class HomeComponent {

    @HostListener('window:keydown', ['$event'])
    spaceEvent(event: any) {
        if(event.ctrlKey && event.keyCode == 32)
            console.log('ctrl + space');
        else if(event.keyCode == 32)
            console.log('space');
    }
}