keyular事件没有被Angular 2 @HostListener捕获

时间:2017-02-02 14:40:48

标签: javascript angular

我有一个谷歌地图应该捕获keyup事件。我的组件是谷歌地图div的父级。它适用于Chrome,它不适用于Firefox或IE(未测试wtith Edge)。

我的组件:

@Component({
  selector: 'dashboard',
  templateUrl: 'dashboard.component.html',
  styleUrls:  ['dashboard.component.css'],
  host: {
    '[attr.tabindex]': '-1'
  },
  providers: []
})
export class DashboardComponent implements OnInit{

  /* some functions and other stuff here 
  * ...
  */

  @HostListener('keyup', ['$event']) keyup(e) {
    console.log('This will be called with Chrome, not with the others.');
  }
};
你经历过同样的经历吗? (如果您需要更多信息,请告诉我)。 感谢

[编辑]
我尝试使用ElementRef捕获keyup事件并将我的事件处理程序设置为onkeyup的{​​{1}}属性,但没有运气

3 个答案:

答案 0 :(得分:4)

尝试聆听window:keyupdocument:keyup事件,而不仅仅是keyup

Source

答案 1 :(得分:0)

出于某种原因,Chrome会将keyup事件传播给父级,而其他浏览器则不会。您可以尝试直接订阅地图的活动。

@ViewChild('myMap')
map: ElementRef;

constructor(private renderer: Renderer) {};

ngOnInit() {
    this.renderer.listen(this.map.nativeElement, 'keyup', (event) => {
        // ...
    });
}

并在模板中:

<div #myMap>...</div>

答案 2 :(得分:0)

有时window:keyup事件无法与@HostListener一起使用,尽管在同一应用程序中的其他情况下也可以使用。尝试改用document:keyup事件。