首页 > 代码库 > [Angular] Angular Global Keyboard Handling With EventManager
[Angular] Angular Global Keyboard Handling With EventManager
If we want to add global event handler, we can use ‘EventManager‘ from ‘@angular/platform-broswer‘.
Now we have a modal component, we want to click ‘Esc‘ key to close the modal.
<au-modal class="auth-modal" *auModalOpenOnClick="[loginButton, signUpButton]" [closeOnClickOutside]="true" [closeOnEsc]="true" [body]="newModelBody"> <!-- Modal body --> </au-modal>
We set two input variables: ‘closeOnEsc‘ for keyboard event. And ‘closeOnClickOutside‘ to click event.
import {Component, Input, OnInit, TemplateRef} from ‘@angular/core‘;import {AuModalService} from ‘./au-modal.service‘;import {EventManager} from ‘@angular/platform-browser‘;@Component({ selector: ‘au-modal‘, templateUrl: ‘./au-modal.component.html‘, styleUrls: [‘./au-modal.component.scss‘]})export class AuModalComponent implements OnInit { @Input() body: TemplateRef<any>; @Input() closeOnClickOutside = true; @Input() closeOnEsc = true; constructor(private auModelService: AuModalService, private eventManage: EventManager) { } ngOnInit() { this.eventManage.addGlobalEventListener(‘window‘, ‘keyup.esc‘, () => { if (this.closeOnEsc) { this.closeModal(); } }) } onClick() { if (this.closeOnClickOutside) { this.closeModal(); } } closeModal() { this.auModelService.close(); } cancelCloseModal(evt: KeyboardEvent) { evt.preventDefault(); evt.stopPropagation(); }}
[Angular] Angular Global Keyboard Handling With EventManager
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。