Skip to content

Instantly share code, notes, and snippets.

@siritori
Last active January 3, 2021 15:31
Show Gist options
  • Save siritori/9c7f3611355b04801db81c67ba85c974 to your computer and use it in GitHub Desktop.
Save siritori/9c7f3611355b04801db81c67ba85c974 to your computer and use it in GitHub Desktop.
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