Alert

The <smart-alert> component is a small confirm dialog: a header, an optional sub-header and message, and a row of buttons. It is what AlertService.show() renders, so every "are you sure?" in the library (for example the remove action of <smart-list>) goes through it. It follows the Base + Standard + Wrapper pattern with an InjectionToken-based extension mechanism. The abstract AlertBaseComponent defines the shared API — a required options input (IAlertOptions), cssClass (alias class), a dismissed output carrying the chosen button (or null), and the invoke(button) / cancel() methods. AlertStandardComponent is the styled default. AlertComponent is the public wrapper that renders AlertStandardComponent by default and accepts a custom replacement via ALERT_STANDARD_COMPONENT_TOKEN.


Usage

<smart-button [options]="openButton">Delete file</smart-button>

@if (isOpen()) {
  <smart-alert [options]="options" (dismissed)="onDismissed($event)" />
}

@if (lastRole(); as role) {
  <p>Last choice: {{ role }}</p>
}

The preview renders the code above in an application that registers every preset (provideSmartPresets(), see Installation) and the English translations; without the presets, a component that has one renders its standard implementation instead, for most components unstyled markup.

Components

AlertComponent (<smart-alert>)

Main wrapper component. Renders AlertStandardComponent by default. When ALERT_STANDARD_COMPONENT_TOKEN is provided, renders the injected component via NgComponentOutlet, passes it options and class and re-emits its dismissed. Use it inline when the alert is part of a template; use AlertService when it has to be opened from code.

AlertStandardComponent (<smart-alert-standard>)

Styled default implementation. Renders a full-screen backdrop (smart:fixed smart:inset-0, translucent gray, darker in dark mode) with a centered panel that carries role="alertdialog", aria-modal="true", aria-labelledby pointing at the header and aria-describedby pointing at the message. Inside: an <h2> header, an optional <h3> sub-header, an optional <p> message and one <button data-role> per entry of options.buttons, right-aligned. Buttons are styled by role — cancel is the secondary white/gray button, destructive is red, everything else is the blue primary — and each button's cssClass is appended. All classes are smart:-prefixed Tailwind with explicit smart:dark: variants.

Keyboard and focus: the first button receives focus when the dialog mounts, Tab and Shift+Tab cycle inside the dialog, Escape (anywhere in the document) cancels. A click on the backdrop cancels unless options.backdropDismiss is false.

AlertBaseComponent (abstract)

Abstract base directive for custom alert implementations. Exposes options as InputSignal<IAlertOptions> (required), cssClass as InputSignal<string> (alias class), the dismissed output, and the computed buttons() and cancelButton() (the first button whose role is cancel, or null). Behaviour lives in the base so a custom template only has to bind it:

MemberWhat it does
invoke(button)Runs button.handler when present, then emits dismissed with the button. A handler that returns false keeps the dialog open (Ionic semantics), except on a button with role cancel, which always dismisses. A cancel button needs no handler.
cancel()Emits dismissed with cancelButton() or null. Runs no handler.
onEscape()Calls cancel(); the standard binds it to document:keydown.escape.
onBackdropClick(event)Calls cancel() when the click landed on the backdrop itself and options.backdropDismiss is not false.
trapFocus(event, container)Keeps Tab / Shift+Tab cycling among the enabled buttons of container.
buttonClasses(button)The role-based Tailwind classes plus the button's own cssClass.
headerId, messageIdUnique ids per instance, for aria-labelledby / aria-describedby.

AlertService

AlertService (provided by SharedServicesModule) opens the dialog without any host element in a template. show(options) creates the component through Angular's createComponent with the service's EnvironmentInjector, attaches the view to ApplicationRef, appends the host element to document.body and returns a promise. The promise resolves with the chosen IAlertButton — after that button's handler has run — or with null when the alert was cancelled and no cancel button exists. On resolution the component is destroyed, its element removed and focus returned to the element that was focused before show().

The service reads ALERT_STANDARD_COMPONENT_TOKEN from its own injector, so a replacement registered at the application root (or in the same module that provides AlertService) is used by every show() call; a token provided deeper in a component tree only affects <smart-alert> instances in that tree.

MethodSignatureNotes
show(options)(options: IAlertOptions) => Promise<IAlertButton | null>Resolves after the button handler ran; await it to sequence work after the decision.

API

Inputs

InputTypeDefaultDescription
optionsInputSignal<IAlertOptions>-Header, sub-header, message and buttons
classInputSignal<string>''External CSS classes (alias for cssClass)

Outputs

OutputPayloadDescription
dismissedIAlertButton | nullFired once, with the chosen button, or null when cancelled without one

IAlertOptions

PropertyTypeDefaultDescription
headerstring-Dialog heading (also the accessible name)
subHeaderstring-Secondary heading under the header
messagestring-Body text (also the accessible description)
backdropDismissbooleantrueWhether a click on the backdrop cancels the alert
buttonsIAlertButton[][]Buttons rendered in order, each styled by its role (see IAlertButton)

IAlertButton

PropertyTypeDefaultDescription
textstring-Visible label
role'cancel' | 'destructive' | string-cancel: the secondary button, and the button Escape and the backdrop dismiss with (its handler does not run then); destructive: red; any other value or none: the blue primary
cssClassstring | string[]-Extra classes appended to the button
handler(value?: unknown) => boolean | void | Record<string, unknown>-Runs on click, before the dialog closes; returning false keeps it open, except on a cancel button

ALERT_STANDARD_COMPONENT_TOKEN

InjectionToken that allows replacing the default AlertStandardComponent with a custom implementation. Provide a Type<AlertBaseComponent> to override. Register it at the application root so that both <smart-alert> and AlertService.show() pick it up.

Extending the base class

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  ViewEncapsulation,
} from '@angular/core';

import {
  ALERT_STANDARD_COMPONENT_TOKEN,
  AlertBaseComponent,
  AlertComponent,
  IAlertOptions,
} from '@smartsoft001/angular';

/**
 * A custom confirm dialog built on `AlertBaseComponent`.
 *
 * The base owns the behaviour: `invoke(button)` runs the button's handler and
 * emits `dismissed`, `cancel()` emits the cancel button, `trapFocus()` keeps
 * Tab inside the panel. It binds no listeners itself, so the template wires
 * the backdrop click, the keydown and the document Escape.
 */
@Component({
  selector: 'docs-custom-alert',
  template: `
    <div class="docs-alert__backdrop" (click)="onBackdropClick($event)">
      <div
        role="alertdialog"
        aria-modal="true"
        tabindex="-1"
        [attr.aria-labelledby]="headerId"
        [attr.aria-describedby]="options().message ? messageId : null"
        [class]="panelClasses()"
        (keydown)="trapFocus($event, panel)"
        #panel
      >
        <h2 class="docs-alert__header" [id]="headerId">
          {{ options().header }}
        </h2>
        @if (options().message) {
          <p class="docs-alert__message" [id]="messageId">
            {{ options().message }}
          </p>
        }
        <footer class="docs-alert__footer">
          @for (button of buttons(); track $index) {
            <button
              type="button"
              class="docs-alert__button"
              [attr.data-role]="button.role ?? null"
              (click)="invoke(button)"
            >
              {{ button.text }}
            </button>
          }
        </footer>
      </div>
    </div>
  `,
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { '(document:keydown.escape)': 'onEscape()' },
})
export class CustomAlertComponent extends AlertBaseComponent {
  panelClasses = computed(() => {
    const classes = ['docs-alert'];
    const extra = this.cssClass();
    if (extra) classes.push(extra);
    return classes.join(' ');
  });
}

/**
 * Registering the implementation against `ALERT_STANDARD_COMPONENT_TOKEN`
 * makes every `<smart-alert>` in this injector render it instead of the
 * standard variation. Provided at the application root, `AlertService.show()`
 * renders it as well.
 */
@Component({
  selector: 'docs-alert-custom-example',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [AlertComponent],
  providers: [
    { provide: ALERT_STANDARD_COMPONENT_TOKEN, useValue: CustomAlertComponent },
  ],
  template: `<smart-alert [options]="options" />`,
})
export class AlertCustomExampleComponent {
  deleted = false;

  options: IAlertOptions = {
    header: 'Delete this record?',
    message: 'The record is removed permanently. This cannot be undone.',
    backdropDismiss: false,
    buttons: [
      { text: 'Cancel', role: 'cancel' },
      {
        text: 'Delete',
        role: 'destructive',
        handler: () => {
          this.deleted = true;
        },
      },
    ],
  };
}

Source

The component lives in packages/shared/angular/src/lib/components/alert and is documented for Claude Code by the angular-components-alert skill.

SmartAlert is a modal alert dialog (role="alertdialog"): a header, an optional sub-header and message, and a row of buttons. It focuses its first button, keeps Tab inside the panel, and cancels on Escape or a click on the backdrop. Most applications do not place it by hand: useAlertService().show(options) opens one and resolves with the button the user chose, and the alert host that SmartProvider renders draws it through the same alert registry key.


Usage

import { useState } from 'react';

import {
  IAlertButton,
  IAlertOptions,
  SmartAlert,
  SmartButton,
} from '@smartsoft001/react';

const options: IAlertOptions = {
  header: 'Delete file?',
  message: 'report-2026.pdf will be removed. This cannot be undone.',
  buttons: [
    { text: 'Cancel', role: 'cancel' },
    { text: 'Delete', role: 'destructive' },
  ],
};

export function AlertUsageExample() {
  const [isOpen, setIsOpen] = useState(false);
  const [lastRole, setLastRole] = useState<string | null>(null);

  const onDismissed = (button: IAlertButton | null) => {
    setLastRole(button?.role ?? null);
    setIsOpen(false);
  };

  return (
    <>
      <SmartButton options={{ click: () => setIsOpen(true) }}>
        Delete file
      </SmartButton>

      {isOpen && <SmartAlert options={options} onDismissed={onDismissed} />}

      {lastRole && <p>Last choice: {lastRole}</p>}
    </>
  );
}

The preview renders the code above in an application that registers every preset (SMART_PRESET_COMPONENTS on SmartProvider, see Installation) and the English translations; without the presets, a component that has one renders its standard implementation instead, for most components unstyled markup.

Exports

All from @smartsoft001/react.

ExportKindWhat it is
SmartAlertcomponentRenders the implementation registered as components.alert on SmartProvider, SmartAlertStandard by default.
SmartAlertStandardcomponentThe default alert dialog: a modal alertdialog on a full-screen backdrop, rendered where it is placed (the alert host of SmartProvider decides where that is).
useAlerthookThe behaviour every alert variant shares: the ids linking the dialog to its header and message, the buttons, and the ways to close it, all reported through onDismissed: - invoke(button) runs button.handler and dismisses with the button, unless the handler of a non-cancel button returned false; - cancel() / onEscape() dismiss with the cancel button (or null), without running its handler; - onBackdropClick(event) cancels on a click on the backdrop itself, unless options.backdropDismiss === false; - trapFocus(event, panel) keeps Tab / Shift+Tab on the panel's buttons.
getAlertButtonClassesfunctionClasses of an alert button by role (cancel -> secondary, destructive -> red, anything else -> primary), followed by its cssClass.

Props and Types

SmartAlertProps

PropTypeDefaultDescription
optionsIAlertOptionsrequiredHeader, message and buttons of the dialog.
className?string—Classes of the dialog panel.
onDismissed?(button: IAlertButton | null) => void—Called with the button that closed the alert, after its handler ran, or the cancel button (role: 'cancel', handler not run) / null on Escape and backdrop click. Not called when the handler of a non-cancel button returns false: the alert stays open.

IAlertOptions

FieldTypeDefaultDescription
header?string—The dialog title (linked through aria-labelledby).
subHeader?string—A smaller line under the header.
message?string—The body text (linked through aria-describedby).
backdropDismiss?booleantrueClick on the backdrop cancels the alert.
buttons?IAlertButton[][]The buttons, in order. Without buttons the dialog can only be cancelled.

SmartAlertKeyEvent

The part of a keyboard event trapFocus reads (DOM or React).

FieldTypeDefaultDescription
keystringrequiredThe pressed key.
shiftKeybooleanrequiredWhether Shift is held (Shift+Tab moves backwards).
preventDefault() => voidrequiredStops the browser from moving the focus itself.

SmartAlertBackdropEvent

The part of a mouse event onBackdropClick reads (DOM or React).

FieldTypeDefaultDescription
targetEventTarget | nullrequiredThe clicked element.
currentTargetEventTarget | nullrequiredThe backdrop element; the alert cancels only when both are the same.

IAlertButton

FieldTypeDefaultDescription
textstringrequiredThe label.
role?'cancel' | 'destructive' | string—'cancel' marks the button Escape and the backdrop use (its handler is not run then); 'destructive' styles it as dangerous.
cssClass?string | string[]—Extra classes of the button.
handler?(value?: unknown) => boolean | void | Record<string, unknown>—Runs on click. Returning false from the handler of a non-cancel button keeps the dialog open.

Opening an alert from code

AlertService.show(options) returns a promise of the chosen IAlertButton (or null on Escape / backdrop click without a cancel button), resolved after the button's handler ran. The alert host of SmartProvider (SmartAlertHost, part of SmartOverlays) renders the dialog at the end of <body> and gives the focus back to the element that had it. See the react-components-overlays skill for the hosts.

Replacing the Implementation

SmartAlert renders the component registered under the 'alert' key of SmartProvider's components, and SmartAlertStandard when nothing is registered there. Every SmartAlert below the provider then renders the registered component, which receives the same props.

There is no preset for this component: register a component of your own that takes SmartAlertProps as components={{ alert: MyAlert }} (the example at the end of this section is one). Pass components as a stable object (a module constant or a memoised value), or the context changes on every render.

The useAlert hook

The behaviour every alert variant shares: the ids linking the dialog to its header and message, the buttons, and the ways to close it, all reported through onDismissed:

  • invoke(button) runs button.handler and dismisses with the button, unless the handler of a non-cancel button returned false;
  • cancel() / onEscape() dismiss with the cancel button (or null), without running its handler;
  • onBackdropClick(event) cancels on a click on the backdrop itself, unless options.backdropDismiss === false;
  • trapFocus(event, panel) keeps Tab / Shift+Tab on the panel's buttons.
ReturnsTypeDescription
headerIdstringId for the header element (aria-labelledby).
messageIdstringId for the message element (aria-describedby).
buttonsIAlertButton[]options.buttons ?? [].
cancelButtonIAlertButton | nullThe button with role: 'cancel', or null.
invoke(button: IAlertButton) => voidClick handler of a button: runs its handler and dismisses with it, unless a non-cancel handler returned false.
cancel() => voidDismisses with the cancel button (or null) without running its handler.
onEscape() => voidSame as cancel, for the Escape key.
onBackdropClick(event: SmartAlertBackdropEvent) => voidCancels on a click on the backdrop element itself, unless options.backdropDismiss === false.
trapFocus(event: SmartAlertKeyEvent, container: HTMLElement) => voidKeeps Tab / Shift+Tab on the panel's buttons; call it from the panel's onKeyDown.
buttonClasses(button: IAlertButton) => stringThe classes of a button (getAlertButtonClasses), by role and cssClass.

A custom dialog builds on useAlert, which supplies the ids, the buttons and every way of closing:

import { useEffect, useState } from 'react';

import {
  IAlertOptions,
  SmartAlert,
  SmartAlertProps,
  SmartProvider,
  useAlert,
} from '@smartsoft001/react';

/**
 * A custom confirm dialog built on `useAlert`.
 *
 * The hook owns the behaviour: `invoke(button)` runs the button's handler and
 * calls `onDismissed`, `onEscape()` dismisses with the cancel button,
 * `trapFocus()` keeps Tab inside the panel. It binds no listeners itself, so
 * the component wires the backdrop click, the keydown and the document Escape.
 */
export function CustomAlert(props: SmartAlertProps) {
  const { options, className } = props;
  const {
    headerId,
    messageId,
    buttons,
    invoke,
    onEscape,
    onBackdropClick,
    trapFocus,
  } = useAlert(props);

  useEffect(() => {
    const listener = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onEscape();
    };

    document.addEventListener('keydown', listener);

    return () => document.removeEventListener('keydown', listener);
  }, [onEscape]);

  return (
    <div className="docs-alert__backdrop" onClick={onBackdropClick}>
      <div
        role="alertdialog"
        aria-modal="true"
        tabIndex={-1}
        aria-labelledby={headerId}
        aria-describedby={options.message ? messageId : undefined}
        className={['docs-alert', className].filter(Boolean).join(' ')}
        onKeyDown={(event) => trapFocus(event, event.currentTarget)}
      >
        <h2 className="docs-alert__header" id={headerId}>
          {options.header}
        </h2>
        {options.message && (
          <p className="docs-alert__message" id={messageId}>
            {options.message}
          </p>
        )}
        <footer className="docs-alert__footer">
          {buttons.map((button, index) => (
            <button
              key={index}
              type="button"
              className="docs-alert__button"
              data-role={button.role}
              onClick={() => invoke(button)}
            >
              {button.text}
            </button>
          ))}
        </footer>
      </div>
    </div>
  );
}

// Registered under 'alert', it renders every <SmartAlert> below the provider
// and the dialogs of AlertService.show(). A module constant: a new object on
// every render would change the context.
const components = { alert: CustomAlert };

export function AlertCustomExample() {
  const [open, setOpen] = useState(true);
  const [deleted, setDeleted] = useState(false);

  const options: IAlertOptions = {
    header: 'Delete this record?',
    message: 'The record is removed permanently. This cannot be undone.',
    backdropDismiss: false,
    buttons: [
      { text: 'Cancel', role: 'cancel' },
      { text: 'Delete', role: 'destructive', handler: () => setDeleted(true) },
    ],
  };

  return (
    <SmartProvider components={components}>
      {open && (
        <SmartAlert options={options} onDismissed={() => setOpen(false)} />
      )}
      {deleted && <p>Record deleted.</p>}
    </SmartProvider>
  );
}

Registered under the alert key, it renders both the SmartAlerts placed by hand and the dialogs of AlertService.show.

Styling

  • className goes on the dialog panel.
  • The standard dialog renders a full-screen backdrop where it is placed; the alert host puts it at the end of <body>. Classes carry smart:dark: variants.

Source

The component lives in packages/shared/react/src/lib/components/alert and is documented for Claude Code by the react-components-alert skill.