Last active
January 3, 2021 15:31
-
-
Save siritori/9c7f3611355b04801db81c67ba85c974 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EventEmitter, Injectable } from '@angular/core'; | |
import { Overlay, OverlayConfig } from '@angular/cdk/overlay'; | |
import { ComponentPortal, ComponentType } from '@angular/cdk/portal'; | |
import { Observable } from 'rxjs'; | |
import { tap } from 'rxjs/operators'; | |
export interface DialogNeed<Return> { | |
close$: EventEmitter<Return>; | |
} | |
export type ComponentProps<TComponent> = { | |
[PropName in keyof TComponent]?: TComponent[PropName]; | |
}; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class DialogService { | |
constructor(private overlay: Overlay) { } | |
open<TComponent extends DialogNeed<TReturn>, TReturn = void>( | |
component: ComponentType<TComponent>, | |
props: ComponentProps<TComponent> = {}, | |
): Observable<TReturn> { | |
const config = new OverlayConfig({ | |
positionStrategy: this.overlay.position().global().centerHorizontally().centerVertically(), | |
hasBackdrop: true, | |
}); | |
const overlayRef = this.overlay.create(config); | |
const portal = new ComponentPortal(component); | |
const componentRef = overlayRef.attach(portal); | |
const instance = componentRef.instance; | |
Object.assign(instance, props); | |
return instance.close$.pipe(tap(() => overlayRef.detach())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment