1- import { DialogConfig , DialogRef } from '@angular/cdk/dialog' ;
1+ import { Dialog , DialogConfig , DialogRef } from '@angular/cdk/dialog' ;
2+ import { DestroyRef , inject , Injector , Signal , Type } from '@angular/core' ;
3+ import { toSignal } from '@angular/core/rxjs-interop' ;
4+ import { map , merge , of , Subject , switchMap } from 'rxjs' ;
25
36const TYPES = Symbol ( 'TYPES' ) ;
47
@@ -22,8 +25,35 @@ export type DialogConfigOf<T extends DialogIoTypes<any, any>> = DialogConfig<
2225 DialogRefOf < T >
2326> ;
2427
25- export function createDialogConfig < T extends DialogIoTypes < any , any > > (
26- config : DialogConfigOf < T > ,
27- ) : typeof config {
28- return config ;
28+ export interface DialogFacade < T extends DialogIoTypes < any , any > > {
29+ launch : ( config ?: DialogConfigOf < T > ) => DialogRefOf < T > ;
30+ ref : Signal < DialogRefOf < T > | undefined > ;
2931}
32+
33+ export const useDialog = < T extends DialogIoTypes < any , any > > (
34+ component : Type < T > ,
35+ configDefaults : Partial < DialogConfigOf < T > > = { } ,
36+ [ service , injector , destroyRef ] = [
37+ inject ( Dialog ) ,
38+ inject ( Injector ) ,
39+ inject ( DestroyRef ) ,
40+ ] ,
41+ ) : DialogFacade < T > => {
42+ const launched$ = new Subject < DialogRefOf < T > > ( ) ;
43+ destroyRef . onDestroy ( ( ) => launched$ . complete ( ) ) ;
44+ return {
45+ launch : ( config : DialogConfigOf < T > = { } ) : DialogRefOf < T > => {
46+ const open = service . open . bind ( service ) ;
47+ const ref = open ( component , { injector, ...configDefaults , ...config } ) ;
48+ launched$ . next ( ref ) ;
49+ return ref ;
50+ } ,
51+ ref : toSignal (
52+ launched$ . pipe (
53+ switchMap ( ( ref ) =>
54+ merge ( of ( ref ) , ref . closed . pipe ( map ( ( ) => undefined ) ) ) ,
55+ ) ,
56+ ) ,
57+ ) ,
58+ } ;
59+ } ;
0 commit comments