简体   繁体   English

Angular 2 @HostListener 未捕获 keyup 事件

[英]keyup event not caught with Angular 2 @HostListener

I have a google maps that should capture keyup events.我有一个 google 地图,可以捕获 keyup 事件。 My component is a parent of the google maps div.我的组件是 google maps div 的父组件。 It works fine with Chrome, it does not with Firefox or IE (not tested wtith Edge).它适用于 Chrome,不适用于 Firefox 或 IE(未使用 Edge 进行测试)。

My component:我的组件:

@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.');
  }
};

Have you experienced the same ?你有过同样的经历吗? (Tell me if you need more info). (如果您需要更多信息,请告诉我)。 Thanks谢谢

[edit] [编辑]
I've tried catching the keyup events by using ElementRef and setting my event handler to the onkeyup property of the elementRef.nativeElement , with no luck我尝试通过使用 ElementRef 并将我的事件处理程序设置为elementRef.nativeElementonkeyup属性来捕获keyup事件,但没有运气

Try listening to the window:keyup or document:keyup event instead of simply keyup .尝试收听window:keyupdocument:keyup事件而不是简单的keyup

Source 来源

Sometimes the window:keyup event fails to work with @HostListener , though it works in other cases in the same application.有时window:keyup事件无法与@HostListener一起@HostListener ,尽管它在同一应用程序中的其他情况下也可以使用。 Try to use the document:keyup event instead.尝试改用document:keyup事件。

For some reason Chrome propogates the keyup event to the parent while other browsers dont.出于某种原因,Chrome 会将 keyup 事件传播给父级,而其他浏览器则不会。 You can try subscribing to the map's event directly.您可以尝试直接订阅地图事件。

@ViewChild('myMap')
map: ElementRef;

constructor(private renderer: Renderer) {};

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

and in the template:并在模板中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM