1
0
mirror of https://github.com/bitwarden/desktop.git synced 2024-10-04 04:58:05 +02:00
bitwarden-desktop/src/app/modal.component.ts

69 lines
2.1 KiB
TypeScript
Raw Normal View History

2018-01-29 15:33:43 +01:00
import * as template from './modal.component.html';
import {
Component,
ComponentFactoryResolver,
EventEmitter,
OnDestroy,
Output,
Type,
ViewChild,
ViewContainerRef,
} from '@angular/core';
@Component({
selector: 'app-modal',
template: `<ng-template #container></ng-template>`,
})
export class ModalComponent implements OnDestroy {
2018-01-29 22:33:38 +01:00
@Output() onClose = new EventEmitter();
@Output() onClosed = new EventEmitter();
@Output() onShow = new EventEmitter();
@Output() onShown = new EventEmitter();
2018-01-29 15:33:43 +01:00
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
parentContainer: ViewContainerRef = null;
fade: boolean = true;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnDestroy() {
document.body.classList.remove('modal-open');
document.body.removeChild(document.querySelector('.modal-backdrop'));
}
show<T>(type: Type<T>, parentContainer: ViewContainerRef, fade: boolean = true): T {
2018-01-29 22:33:38 +01:00
this.onShow.emit();
2018-01-29 15:33:43 +01:00
this.parentContainer = parentContainer;
this.fade = fade;
document.body.classList.add('modal-open');
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop' + (this.fade ? ' fade' : '');
document.body.appendChild(backdrop);
const factory = this.componentFactoryResolver.resolveComponentFactory<T>(type);
const componentRef = this.container.createComponent<T>(factory);
2018-01-29 18:14:19 +01:00
document.querySelector('.modal-dialog').addEventListener('click', (e: Event) => {
e.stopPropagation();
});
for (const closeElement of document.querySelectorAll('.modal, .modal *[data-dismiss="modal"]')) {
closeElement.addEventListener('click', (event) => {
this.close();
});
}
2018-01-29 22:33:38 +01:00
this.onShown.emit();
2018-01-29 15:33:43 +01:00
return componentRef.instance;
}
close() {
2018-01-29 22:33:38 +01:00
this.onClose.emit();
this.onClosed.emit();
2018-01-29 15:33:43 +01:00
if (this.parentContainer != null) {
this.parentContainer.clear();
}
}
}