bitwarden-estensione-browser/libs/angular/src/components/modal/dynamic-modal.component.ts

80 lines
2.1 KiB
TypeScript
Raw Normal View History

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