diff --git a/components/modal/nz-modal.component.ts b/components/modal/nz-modal.component.ts index 1dc74c1ea5e..182ee5bda78 100644 --- a/components/modal/nz-modal.component.ts +++ b/components/modal/nz-modal.component.ts @@ -8,7 +8,6 @@ import { ComponentRef, ElementRef, EventEmitter, - HostListener, Inject, Injector, Input, @@ -24,7 +23,7 @@ import { ViewContainerRef } from '@angular/core'; -import { Observable, Subject } from 'rxjs'; +import { fromEvent, Observable, Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { NzMeasureScrollbarService } from '../core/services/nz-measure-scrollbar.service'; @@ -111,12 +110,6 @@ export class NzModalComponent extends NzModalRef impleme @ViewChild('bodyContainer', { read: ViewContainerRef }) bodyContainer: ViewContainerRef; @Input() @InputBoolean() nzKeyboard: boolean = true; - @HostListener('keydown', [ '$event' ]) - public onKeyDown(event: KeyboardEvent): void { - if (event.keyCode === ESCAPE && this.nzKeyboard) { - this.onClickOkCancel('cancel'); - } - } get hidden(): boolean { return !this.nzVisible && !this.animationState; @@ -149,6 +142,7 @@ export class NzModalComponent extends NzModalRef impleme ngOnInit(): void { this.i18n.localeChange.pipe(takeUntil(this.unsubscribe$)).subscribe(() => this.locale = this.i18n.getLocaleData('Modal')); + fromEvent(this.document.body, 'keydown').pipe(takeUntil(this.unsubscribe$)).subscribe((e: KeyboardEvent) => this.keydownListener(e)); if (this.isComponent(this.nzContent)) { this.createDynamicComponent(this.nzContent as Type); // Create component along without View @@ -205,6 +199,12 @@ export class NzModalComponent extends NzModalRef impleme }); } + keydownListener(event: KeyboardEvent): void { + if (event.keyCode === ESCAPE && this.nzKeyboard) { + this.onClickOkCancel('cancel'); + } + } + open(): void { this.changeVisibleFromInside(true); } diff --git a/components/modal/nz-modal.spec.ts b/components/modal/nz-modal.spec.ts index 32018a62e1e..eccc0c9adc9 100644 --- a/components/modal/nz-modal.spec.ts +++ b/components/modal/nz-modal.spec.ts @@ -194,12 +194,12 @@ describe('modal testing (legacy)', () => { it('should be closed when clicking ESC', fakeAsync(() => { // click 'ESC' key - dispatchKeyboardEvent(modalElement, 'keydown', ESCAPE); + dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); fixture.detectChanges(); expectModalDestroyed(tempModalId, false); modalInstance.nzKeyboard = true; - dispatchKeyboardEvent(modalElement, 'keydown', ESCAPE); + dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); flush(); fixture.detectChanges(); expectModalDestroyed(tempModalId, true);