angular 全局監聽鍵盤事件

  • 技術點:使用EventManager
  • 根模塊中不要引用,組件模塊中引用
    import { EventManager } from '@angular/platform-browser';
  • 組件constructor中實例化對象
    constructor(private eventManager:EventManager){}
  • ngOnInit中註冊全局監聽
ngOnInit(): void {
    this.eventManager.addGlobalEventListener('window','keyup.esc',()=>{
      alert('你點擊了ESC');
    });
}

上面的代碼是監聽當WEB頁面中按下esc按鍵,則會彈出模態提示框,完整代碼以下css

import { Component, OnInit } from '@angular/core';
 import { FormsModule } from '@angular/forms';
 import { EventManager } from '@angular/platform-browser';
    
    
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
 })
 export class AppComponent implements OnInit {
   ngOnInit(): void {
     this.eventManager.addGlobalEventListener('window','keyup.esc',()=>{
       alert('你點擊了ESC');
     });
   }
 
   constructor(
     private eventManager:EventManager
   ){}
 }
相關文章
相關標籤/搜索