2021-08-26 10:04:29 +02:00
|
|
|
import {
|
|
|
|
AfterViewInit,
|
|
|
|
ChangeDetectorRef,
|
|
|
|
Component,
|
|
|
|
ComponentRef,
|
|
|
|
ElementRef,
|
|
|
|
OnDestroy,
|
|
|
|
Type,
|
|
|
|
ViewChild,
|
|
|
|
ViewContainerRef
|
|
|
|
} from '@angular/core';
|
|
|
|
|
2021-10-21 00:13:37 +02:00
|
|
|
import {
|
|
|
|
ConfigurableFocusTrap,
|
|
|
|
ConfigurableFocusTrapFactory,
|
|
|
|
} from '@angular/cdk/a11y';
|
|
|
|
|
2021-08-31 16:35:20 +02:00
|
|
|
import { ModalService } from '../../services/modal.service';
|
|
|
|
|
2021-08-26 10:04:29 +02:00
|
|
|
import { ModalRef } from './modal.ref';
|
|
|
|
|
|
|
|
@Component({
|
|
|
|
selector: 'app-modal',
|
|
|
|
template: '<ng-template #modalContent></ng-template>',
|
|
|
|
})
|
|
|
|
export class DynamicModalComponent implements AfterViewInit, OnDestroy {
|
|
|
|
componentRef: ComponentRef<any>;
|
|
|
|
|
|
|
|
@ViewChild('modalContent', { read: ViewContainerRef, static: true }) modalContentRef: ViewContainerRef;
|
|
|
|
|
|
|
|
childComponentType: Type<any>;
|
|
|
|
setComponentParameters: (component: any) => void;
|
|
|
|
|
2021-10-21 00:13:37 +02:00
|
|
|
private focusTrap: ConfigurableFocusTrap;
|
|
|
|
|
2021-08-31 16:35:20 +02:00
|
|
|
constructor(private modalService: ModalService, private cd: ChangeDetectorRef,
|
2021-10-21 00:13:37 +02:00
|
|
|
private el: ElementRef<HTMLElement>, private focusTrapFactory: ConfigurableFocusTrapFactory,
|
|
|
|
public modalRef: ModalRef) { }
|
2021-08-26 10:04:29 +02:00
|
|
|
|
|
|
|
ngAfterViewInit() {
|
|
|
|
this.loadChildComponent(this.childComponentType);
|
|
|
|
if (this.setComponentParameters != null) {
|
|
|
|
this.setComponentParameters(this.componentRef.instance);
|
|
|
|
}
|
|
|
|
this.cd.detectChanges();
|
|
|
|
|
|
|
|
this.modalRef.created(this.el.nativeElement);
|
2021-10-21 00:13:37 +02:00
|
|
|
this.focusTrap = this.focusTrapFactory.create(this.el.nativeElement.querySelector('.modal-dialog'));
|
|
|
|
if (this.el.nativeElement.querySelector('[appAutoFocus]') == null) {
|
|
|
|
this.focusTrap.focusFirstTabbableElementWhenReady();
|
|
|
|
}
|
2021-08-26 10:04:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
loadChildComponent(componentType: Type<any>) {
|
2021-08-31 16:35:20 +02:00
|
|
|
const componentFactory = this.modalService.resolveComponentFactory(componentType);
|
2021-08-26 10:04:29 +02:00
|
|
|
|
|
|
|
this.modalContentRef.clear();
|
|
|
|
this.componentRef = this.modalContentRef.createComponent(componentFactory);
|
|
|
|
}
|
|
|
|
|
|
|
|
ngOnDestroy() {
|
|
|
|
if (this.componentRef) {
|
|
|
|
this.componentRef.destroy();
|
|
|
|
}
|
2021-10-21 00:13:37 +02:00
|
|
|
this.focusTrap.destroy();
|
2021-08-26 10:04:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
close() {
|
|
|
|
this.modalRef.close();
|
|
|
|
}
|
2021-10-21 00:13:37 +02:00
|
|
|
|
|
|
|
getFocus() {
|
|
|
|
const autoFocusEl = this.el.nativeElement.querySelector('[appAutoFocus]') as HTMLElement;
|
|
|
|
autoFocusEl?.focus();
|
|
|
|
}
|
2021-08-26 10:04:29 +02:00
|
|
|
}
|