2
  • 技术点:使用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按键,则会弹出模态提示框,完整代码如下

 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
   ){}
 }

葬天尘
360 声望7 粉丝

引用和评论

0 条评论