|
| 1 | +import {ComponentType, GlobalPositionStrategy, Overlay, OverlayConfig} from '@angular/cdk/overlay'; |
| 2 | +import {ComponentPortal} from '@angular/cdk/portal'; |
| 3 | +import {Injectable, Injector, StaticProvider} from '@angular/core'; |
| 4 | + |
| 5 | +import {NgxAbsDialogRef} from './NgxAbsDialogRef'; |
| 6 | +import {NGX_ABS_DIALOG_DATA} from './tokens'; |
| 7 | + |
| 8 | +export interface INgxAbsDialogConfig<T = any> extends Omit<OverlayConfig, 'positionStrategy'> { |
| 9 | + data?: T; |
| 10 | + backdropClickClose?: boolean; |
| 11 | +} |
| 12 | + |
| 13 | +@Injectable() |
| 14 | +export class NgxAbsDialog { |
| 15 | + |
| 16 | + constructor( |
| 17 | + private overlay: Overlay, |
| 18 | + private injector: Injector |
| 19 | + ) { |
| 20 | + } |
| 21 | + |
| 22 | + static createConfig<T>(config?: INgxAbsDialogConfig<T>): INgxAbsDialogConfig<T> { |
| 23 | + return { |
| 24 | + backdropClickClose: true, |
| 25 | + hasBackdrop: true, |
| 26 | + disposeOnNavigation: false, |
| 27 | + ...config |
| 28 | + }; |
| 29 | + } |
| 30 | + |
| 31 | + open<T, R = any>( |
| 32 | + cmp: ComponentType<any>, |
| 33 | + config?: INgxAbsDialogConfig<T>, |
| 34 | + providers?: StaticProvider[] |
| 35 | + ): NgxAbsDialogRef<T, R> { |
| 36 | + const configOptions = NgxAbsDialog.createConfig(config); |
| 37 | + const overlay = this.overlay.create(configOptions); |
| 38 | + const position = new GlobalPositionStrategy(); |
| 39 | + overlay.updatePositionStrategy(position); |
| 40 | + position.centerHorizontally(); |
| 41 | + position.centerVertically(); |
| 42 | + const modalRef = new NgxAbsDialogRef<T, R>(overlay, configOptions); |
| 43 | + const cmpPortal = new ComponentPortal( |
| 44 | + cmp, null, Injector.create({ |
| 45 | + providers: [ |
| 46 | + {provide: NGX_ABS_DIALOG_DATA, useValue: config?.data}, |
| 47 | + {provide: NgxAbsDialogRef, useValue: modalRef}, |
| 48 | + ...(providers || []) |
| 49 | + ], |
| 50 | + parent: this.injector |
| 51 | + }) |
| 52 | + ); |
| 53 | + overlay.attach(cmpPortal); |
| 54 | + return modalRef; |
| 55 | + } |
| 56 | + |
| 57 | +} |
0 commit comments