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