# Dialog

A modal window that asks the user to finish a focused task, such as editing a record, before returning to the page. Built on the native `<dialog>` element, so focus trapping, stacking and Escape come from the browser.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-dialog`, `[vigDialogFooter]`, `ng-template[vigDialogContent]`
- Source: [libs/ui/src/lib/organisms/dialog/dialog.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/organisms/dialog/dialog.ts)

```typescript title="Import"
import { Dialog, DialogFooter, DialogContent, Dialogs } from '@vigdx/ui/dialog';
```

## Basic

Two-way bind `[(open)]` to a signal and give the dialog a `heading`. Mark the action row with `vigDialogFooter`; `class="contents"` lets its buttons sit directly in the right-aligned footer.

```typescript title="dialog-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { Dialog, DialogFooter } from '@vigdx/ui/dialog';
import { InputField } from '@vigdx/ui/input-field';

@Component({
  selector: 'app-dialog-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, Dialog, DialogFooter, InputField],
  template: `
    <div class="flex flex-wrap items-center gap-3">
      <vig-button label="Edit profile" (click)="open.set(true)" />
      <span class="text-sm text-muted-foreground">Name: {{ name() }}</span>
    </div>

    <vig-dialog heading="Edit profile" [(open)]="open">
      <div class="flex flex-col gap-4 pt-1">
        <vig-input label="Full name" [(value)]="draft" />
        <vig-input label="Email" type="email" value="ada@example.com" />
      </div>
      <div vigDialogFooter class="contents">
        <vig-button label="Cancel" variant="secondary" (click)="open.set(false)" />
        <vig-button label="Save" (click)="save()" />
      </div>
    </vig-dialog>
  `,
})
export class DialogBasicDemo {
  protected readonly open = signal(false);
  protected readonly name = signal('Ada Lovelace');
  protected readonly draft = signal('Ada Lovelace');

  protected save(): void {
    this.name.set(this.draft());
    this.open.set(false);
  }
}
```

## Scrollable content

The dialog is capped at 85% of the viewport height; longer content scrolls inside the body while the header and footer stay put. `width` sets the width, capped at the viewport.

```typescript title="dialog-scrollable.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { Dialog, DialogFooter } from '@vigdx/ui/dialog';

@Component({
  selector: 'app-dialog-scrollable',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, Dialog, DialogFooter],
  template: `
    <vig-button label="Read the terms" variant="secondary" (click)="open.set(true)" />

    <vig-dialog heading="Terms of service" width="40rem" [(open)]="open">
      @for (section of sections; track section) {
        <h3 class="mt-4 mb-1 font-semibold first:mt-0">{{ section }}. Section {{ section }}</h3>
        <p>
          The body scrolls on its own while the header and the footer stay in place, so the actions
          are always within reach.
        </p>
      }
      <div vigDialogFooter class="contents">
        <vig-button label="Decline" variant="secondary" (click)="open.set(false)" />
        <vig-button label="Accept" (click)="open.set(false)" />
      </div>
    </vig-dialog>
  `,
})
export class DialogScrollableDemo {
  protected readonly open = signal(false);
  protected readonly sections = Array.from({ length: 12 }, (_, i) => i + 1);
}
```

## Dismiss options

By default the X button, a backdrop click and Escape all close the dialog. Turn them off with `closable`, `closeOnBackdropClick` (formerly `dismissable`) and `closeOnEscape` when the user must decide explicitly — and then always offer a button that closes it.

```typescript title="dialog-dismiss.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { Dialog, DialogFooter } from '@vigdx/ui/dialog';
import { Spinner } from '@vigdx/ui/spinner';

@Component({
  selector: 'app-dialog-dismiss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, Dialog, DialogFooter, Spinner],
  template: `
    <vig-button label="Start export" (click)="open.set(true)" />

    <vig-dialog
      heading="Exporting data"
      [closable]="false"
      [closeOnBackdropClick]="false"
      [closeOnEscape]="false"
      [(open)]="open"
    >
      <div class="flex items-center gap-3">
        <vig-spinner size="sm" />
        <p>Neither the backdrop nor Escape closes this dialog; only the button does.</p>
      </div>
      <div vigDialogFooter class="contents">
        <vig-button label="Cancel export" variant="secondary" (click)="open.set(false)" />
      </div>
    </vig-dialog>
  `,
})
export class DialogDismissDemo {
  protected readonly open = signal(false);
}
```

## Overlays inside a dialog

A modal dialog makes the rest of the page inert, including the overlay container that select, date picker and menu panels render into. `provideVigdxUi()` moves that container into the open dialog's top layer, so panels stay clickable and Escape closes the open panel before the dialog.

```typescript title="dialog-nested-overlays.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { Dialog, DialogFooter } from '@vigdx/ui/dialog';
import { Select, type SelectOption } from '@vigdx/ui/select';

@Component({
  selector: 'app-dialog-nested-overlays',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, Dialog, DialogFooter, Select],
  template: `
    <vig-button label="Invite member" (click)="open.set(true)" />

    <vig-dialog heading="Invite member" width="28rem" [(open)]="open">
      <div class="flex flex-col gap-4 pt-1">
        <vig-select label="Team" [options]="teams" [filter]="true" [(value)]="team" />
        <vig-select label="Role" [options]="roles" [(value)]="role" />
      </div>
      <div vigDialogFooter class="contents">
        <vig-button label="Cancel" variant="secondary" (click)="open.set(false)" />
        <vig-button label="Send invite" [disabled]="!team()" (click)="open.set(false)" />
      </div>
    </vig-dialog>
  `,
})
export class DialogNestedOverlaysDemo {
  protected readonly open = signal(false);
  protected readonly team = signal<string | null>(null);
  protected readonly role = signal<string | null>('member');
  protected readonly teams: SelectOption[] = [
    { value: 'design', label: 'Design' },
    { value: 'engineering', label: 'Engineering' },
    { value: 'marketing', label: 'Marketing' },
    { value: 'sales', label: 'Sales' },
    { value: 'support', label: 'Support' },
  ];
  protected readonly roles: SelectOption[] = [
    { value: 'viewer', label: 'Viewer' },
    { value: 'member', label: 'Member' },
    { value: 'admin', label: 'Admin' },
  ];
}
```

```typescript title="app-config.ts"
import type { ApplicationConfig } from '@angular/core';
import { provideVigdxUi } from '@vigdx/ui/core';

// Once per app: lets select, date picker and menu panels work inside the
// native top layer of an open vig-dialog or vig-drawer.
export const appConfig: ApplicationConfig = {
  providers: [provideVigdxUi()],
};
```

## Open from code

The `Dialogs` service opens a component in a `vig-dialog` without a host element: `open()` returns a `VigDialogRef` whose `closed` promise settles with the result. The content keeps `injectDialogRef()` in a public `dialogRef` field, which types the data and the result for the caller, and closes with `dialogRef.close(result)`; its `beforeClose` guard asks before Escape, the backdrop, the X button or Cancel discard edits.

```typescript title="dialog-service.ts"
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { Dialogs } from '@vigdx/ui/dialog';

import { Customer, EditCustomerDialog } from './edit-customer-dialog';

@Component({
  selector: 'app-dialog-service',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button],
  template: `
    <div class="flex flex-wrap items-center gap-3">
      <vig-button label="Edit customer" (click)="edit()" />
      <span class="text-sm text-muted-foreground" aria-live="polite">{{ status() }}</span>
    </div>
  `,
})
export class DialogServiceDemo {
  private readonly dialogs = inject(Dialogs);
  private customer: Customer = { name: 'Ada Lovelace', email: 'ada@example.com' };
  protected readonly status = signal('Ada Lovelace · ada@example.com');

  protected async edit(): Promise<void> {
    // The result and data types come from EditCustomerDialog's dialogRef.
    const ref = this.dialogs.open(EditCustomerDialog, {
      heading: 'Edit customer',
      data: this.customer,
    });
    const saved = await ref.closed; // Customer | undefined
    if (saved) {
      this.customer = saved;
      this.status.set(`${saved.name} · ${saved.email}`);
    } else {
      this.status.set('No changes saved');
    }
  }
}
```

```typescript title="edit-customer-dialog.ts"
import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { Confirm } from '@vigdx/ui/confirm-dialog';
import { injectDialogRef } from '@vigdx/ui/dialog';
import { InputField } from '@vigdx/ui/input-field';

export interface Customer {
  name: string;
  email: string;
}

/** The dialog's content: typed data in, a typed result out. */
@Component({
  selector: 'app-edit-customer-dialog',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, InputField],
  template: `
    <div class="flex flex-col gap-4 pt-1">
      <vig-input label="Full name" [(value)]="name" />
      <vig-input label="Email" type="email" [(value)]="email" />
      <div class="flex justify-end gap-2 pt-2">
        <!-- requestClose() runs the guard below; close() skips it. -->
        <vig-button label="Cancel" variant="secondary" (click)="dialogRef.requestClose()" />
        <vig-button label="Save" (click)="save()" />
      </div>
    </div>
  `,
})
export class EditCustomerDialog {
  // Public, so Dialogs.open() infers the result and data types from it.
  readonly dialogRef = injectDialogRef<Customer, Customer>();
  private readonly customer = this.dialogRef.data;
  private readonly confirm = inject(Confirm);

  protected readonly name = signal(this.customer.name);
  protected readonly email = signal(this.customer.email);
  private readonly dirty = computed(
    () => this.name() !== this.customer.name || this.email() !== this.customer.email,
  );

  constructor() {
    // Escape, the backdrop, the X button and Cancel ask before discarding edits.
    this.dialogRef.beforeClose = () =>
      !this.dirty() ||
      this.confirm.ask({
        heading: 'Discard changes?',
        message: 'Your edits to this customer will be lost.',
        acceptLabel: 'Discard',
        rejectLabel: 'Keep editing',
        variant: 'error',
      });
  }

  protected save(): void {
    this.dialogRef.close({ name: this.name(), email: this.email() });
  }
}
```

## Dialogs service

`inject(Dialogs).open(component, options)` renders the component in a `vig-dialog` appended to `<body>`, with the same native modal, dismissal and exit transition as the declarative dialog. One helper connects the content: `injectDialogRef<Result, Data>()` gives it the data (`data`) and the way out (`close`, `requestClose`, `beforeClose`). Declared as a public `dialogRef` field, it also types `open()`: the caller must pass matching `data`, and `closed` resolves with the result type, with no generics at the call site.

```typescript
export class EditCustomerDialog {
  // R = the result, D = the data. Public, so open() infers both.
  readonly dialogRef = injectDialogRef<Customer, Customer>();

  save(): void {
    this.dialogRef.close({ ...this.dialogRef.data, name: this.name() });
  }
}
```

```typescript
const ref = this.dialogs.open(EditCustomerDialog, {
  data: customer,           // required and type-checked: EditCustomerDialog declares it
  heading: 'Edit customer', // or ariaLabel for a dialog without a heading
  size: 'lg',               // sm | md (default) | lg: the --container-dialog-* tokens
  closeOnBackdropClick: false,
  closeOnEscape: true,
  closeOnNavigation: true,  // default: a route (path) change closes it
  beforeClose: (result) => result !== undefined || confirmDiscard(),
  injector: this.injector,  // = inject(Injector) in a field: this component's providers
  providers: [{ provide: CUSTOMER_API, useClass: CustomerApi }],
});

ref.state();        // signal: 'open' | 'closing' | 'closed'
await ref.closed;   // Customer | undefined, after the exit transition
ref.requestClose(); // runs beforeClose; ref.close(value) does not
```

Widths are presets from tokens rather than CSS lengths, and there is no z-index option: each dialog opens in the browser's top layer, above everything opened before it. Open an `<ng-template>` the same way; its context is the ref:

```html
<ng-template #note let-ref>
  <p>{{ ref.data }}</p>
  <vig-button label="Got it" (click)="ref.close(true)" />
</ng-template>
```

```typescript
readonly note = viewChild.required<TemplateRef<DialogTemplateContext<boolean, string>>>('note');

open(): void {
  this.dialogs.open(this.note(), {
    heading: 'Release notes',
    data: 'Exports now include archived projects.',
  });
}
```

- **Focus** starts on the content's `autofocus` element, else on its first focusable element, else on the X button, and returns to the element that opened the dialog once it has closed.
- **Stacking**: a dialog opened from another one opens on top of it; Escape closes the newest first. `openDialogs()` lists the open ones and `closeAll()` closes them.
- **Closing**: Escape, the backdrop, the X button and `requestClose()` run `beforeClose`; `close(result)`, `closeAll()`, a navigation and the end of the application do not. A guard that never settles blocks the user's ways out (development builds warn after 10 seconds).
- **Server rendering**: on the server `open()` renders nothing and returns a ref that is already `closed` and whose `closed` promise never settles, so a dialog opened while a page initializes appears once the browser takes over, and code awaiting the result runs only there.
- **Injection**: `Dialogs` is provided in root. Called from a constructor or field initializer, `open()` uses the caller's injector; from an event handler it uses the root injector, so pass `injector` (a field set to `inject(Injector)`) for the content to reach the opener's component and route providers.
- **Typing**: `open()` reads the result and data types from a _public_ `readonly dialogRef` field created by `injectDialogRef()`. A private or protected field is invisible to the type system; the ref is then `VigDialogRef<unknown, unknown>`.
- **Navigation**: with `closeOnNavigation` (the default) a change of the route path closes the dialog without `beforeClose`; query and fragment changes, and URL changes before the dialog first rendered (initial navigation, redirects), do not.
- **Native closes**: a `<form method="dialog">` in the content goes through `requestClose()` with the submit button's value. A close the browser forces (repeated Escape presses without user activation) is accepted as a dismissal rather than re-shown.

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="dialog"][data-part="panel"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="dialog"]`

| Part | Element | data-state |
| --- | --- | --- |
| `panel` | The native `<dialog>`; style the backdrop with `::backdrop`. | `open, closed` |
| `header` | The header row: heading and close button. |   |
| `heading` | The `<h2>` of `heading`. |   |
| `close` | The close button (`closable`). |   |
| `body` | The scrolling body. |   |
| `footer` | The `[vigDialogFooter]` row. |   |

| Attribute | Meaning |
| --- | --- |
| `data-opening` | On the overlay element (panel or `<dialog>`) while its entrance transition plays; removed once it settles (2s at most). Style the entrance with `data-opening:` utilities. |
| `data-closing` | On the overlay element while its exit transition plays, before it closes; removed once it settles (2s at most). Style the closed look with `data-closing:` utilities. |

## Accessibility

- Follows the WAI-ARIA APG modal dialog pattern using the native `<dialog>` and `showModal()`: the page behind is inert, focus moves into the dialog and Tab stays inside it.
- The dialog is named by its `heading` through `aria-labelledby`. Without a header, pass `ariaLabel`.
- Escape closes the dialog unless `closeOnEscape` is off; when it closes, the browser returns focus to the element that opened it. Dismissal is declared with the native `closedby` attribute where supported (`closeOnEscape` off maps to `closedby="none"`), with a script fallback elsewhere.
- With `closeOnBackdropClick`, a backdrop click closes the dialog only when the press and the release both land outside it, so dragging a text selection out of the dialog never loses the user's input. Scrolling over the backdrop or past the end of the content does not scroll the page behind.
- The close button is labelled by `closeAriaLabel` (localized by default). If you hide it with `closable`, keep a visible way to close the dialog.
- On open, the browser focuses the first focusable element — the close button while `closable` is on. Add `autofocus` to the field the user should start with (`vig-button` takes an `autofocus` input too).
- Opening and closing fade (and scale, unless the user prefers reduced motion); the close waits for the fade before the dialog leaves the top layer.

## Lazy content

Projected content is created with the `vig-dialog`, even while it is closed. Wrap a heavy body (a form that loads data, a chart) in `<ng-template vigDialogContent>` instead: it is created when the dialog opens and destroyed once it has closed, after the exit transition.

## API

### Dialog

Selector: `vig-dialog` · Kind: component

Modal dialog on top of the native `<dialog>` element: the platform provides the focus trap, top-layer stacking, Escape handling and focus restore — no overlay library involved. Deliberately not draggable/resizable. While it plays its entrance or exit transition, the animating element carries `data-opening` or `data-closing` (stable hooks for styling and for waiting in tests; see the theming guide). data-opening data-closing

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `ariaLabel` | `string \| undefined` | `undefined` | — |
| `closable` | `boolean` | `true` | Show the X button in the header row. |
| `closeAriaLabel` | `string \| undefined` | `undefined` | — |
| `closeOnBackdropClick` | `boolean \| undefined` | `undefined` | Close when the backdrop is clicked (press and release both outside the box, so dragging a text selection out never dismisses). Default `true`. |
| `closeOnEscape` | `boolean` | `true` | Close on Escape / the back gesture; off also disables backdrop dismissal natively. |
| `dismissable` | `boolean` | `true` | **Deprecated**: Use `closeOnBackdropClick`; still honored when it is unset. |
| `header` | `string \| undefined` | `undefined` | **Deprecated**: Use `heading`; still honored when `heading` is unset. |
| `heading` | `string \| undefined` | `undefined` | Visible title, which also names the panel (`aria-labelledby`). |
| `open` (model) | `boolean` | `false` | Two-way: drive with a signal, e.g. `[(open)]="editorOpen"`. |
| `width` | `string` | `'var(--container-dialog-md)'` | CSS width, capped at the viewport by max-width. Defaults to the `--container-dialog-md` token, shared with `Dialogs`' `size: 'md'`. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `openChange` | `boolean` | Two-way: drive with a signal, e.g. `[(open)]="editorOpen"`. |

### Dialogs

Kind: injectable

Opens dialogs from code (PrimeNG `DialogService` / CDK `Dialog` territory) on top of `vig-dialog`: native modal `<dialog>`, top layer, `closedby` dismissal and exit transitions. No host element to place.

**Example :**

```ts
// EditUser declares `readonly dialogRef = injectDialogRef<User, { id: string }>()`
const ref = inject(Dialogs).open(EditUser, { heading: 'Edit user', data: { id } });
const saved = await ref.closed; // User | undefined
```

Focus moves to the content's `autofocus` element, else its first focusable one, and returns to the opener on close. Dialogs stack: the newest is on top and Escape closes it first.

Server rendering: `open()` is a no-op that returns an inert ref (state `closed`, `closed` never settles), so code that opens a dialog while a page initializes renders nothing on the server and opens it in the browser.

#### Methods

| Signature | Description |
| --- | --- |
| `closeAll(): void` | Closes every open dialog, newest first, without consulting `beforeClose`. |
| `open(component: Type<C>, ...args: DialogOpenArgs<DialogResultOf<C>, DialogDataOf<C>>): VigDialogRef<DialogResultOf<C>, DialogDataOf<C>>` | Opens a component in a modal dialog. The result and data types come from the component's `dialogRef` field, so `data` is checked and `closed` resolves with the component's result type. |
| `open(template: TemplateRef<DialogTemplateContext<R, D>> \| TemplateRef<unknown>, ...args: DialogOpenArgs<R, D>): VigDialogRef<R, D>` | Opens an `<ng-template let-ref>` in a modal dialog; `ref` is the `VigDialogRef`. Type the template as `TemplateRef<DialogTemplateContext<R, D>>` to type the ref; a `TemplateRef<unknown>` opens with `unknown` types. |

### Templates and directives

| Selector | Export | Description |
| --- | --- | --- |
| `[vigDialogFooter]` | `DialogFooter` | Marks the footer (action row) content of a vig-dialog. |
| `ng-template[vigDialogContent]` | `DialogContent` | Body content of a vig-dialog created only while it is shown: when it opens, and destroyed once it has closed (after the exit transition). Projected content, by contrast, lives as long as the vig-dialog does. **Example :** `<vig-dialog [(open)]="editing" heading="Edit"> <ng-template vigDialogContent><app-editor /></ng-template> </vig-dialog>` |
