cdk / dialog / Function

useDialog

Generic types:T

Assembles a facade object for a specific dialog component type with optional default configurations, enabling a satisfying development experience working with Angular CDK dialogs.

Presentation

function useDialog(
  component: Type<T>,
  configDefaults: Partial<DialogConfigOf<T>> = {},
  [service, injector, destroyRef, componentFactoryResolver, viewContainerRef]: [
    Dialog,
    Injector,
    DestroyRef,
    ComponentFactoryResolver,
    ViewContainerRef | undefined,
  ] = [
    inject(Dialog),
    inject(Injector),
    inject(DestroyRef),
    inject(ComponentFactoryResolver),
    inject(ViewContainerRef, { optional: true }) ?? undefined, // available only in components
  ],
): DialogFacade<T>;

Returns

DialogFacade<T> -

a DialogFacade object for the specified dialog component

Parameters

NameTypeDescription
component
Type<T>

dialog component class, extending DialogIoTypes

configDefaults
Partial<DialogConfigOf<T>>

default configuration for the dialog

[ service, injector, destroyRef, componentFactoryResolver, viewContainerRef, ]
[Dialog, Injector, DestroyRef, ComponentFactoryResolver, ViewContainerRef | undefined]

Example usage

// Declare dialog input and output types on the dialog class.
@Component({ ... })
class MyDialog extends DialogIoTypes<
  { someData: object }, // Input type
  { someResult: object } // Output type
> {}
 @Component({ ... })
 class HostComponent {
   private myDialog = useDialog(MyDialog, { disableClose: true });

   onFoo(): void {
     // Typed dialog launching experience.
     const ref = this.myDialog.launch({ data: { inputs: "values" } });
     // Typed dialog output
     ref.closed.subscribe((output) => { ... });
   }

   onBar(): void {
     // Access the current DialogRef anytime.
     this.myDialog.ref()?.close();
   }

   constructor() {
     effect(() => {
       const ref = this.myDialog.ref();
       // Listen to the dialog launching and closing
       if (ref) console.log("Dialog launched");
       else console.log("Dialog closed or never launched");
     });
   }
 }