@molecule/app-danger-zone-angular

Feature · danger-zone · App (browser) · v1.1.4 · Apache-2.0

DangerZoneSection + ConfirmDialog for destructive actions (delete account, reset, revoke)

npm install @molecule/app-danger-zone-angular

npm · Source on GitHub

How it works

@molecule/app-danger-zone-angular is a ready-made danger-zone feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { Component } from '@angular/core'
import { DangerZoneSection } from '@molecule/app-danger-zone-angular'

@Component({
  selector: 'app-account',
  standalone: true,
  imports: [DangerZoneSection],
  template: `
    <div
      mol-danger-zone-section
      title="Delete account"
      description="This permanently removes your account and all data."
      actionLabel="Delete account"
      (click)="openConfirm()"
    ></div>
  `,
})
export class Account {
  readonly openConfirm = (): void => {
    console.log('open delete-account confirmation')
  }
}

Works with: @molecule/app-angular, @molecule/app-ui, @molecule/app-ui-angular

Reference

Angular destructive-action primitives — the counterpart of @molecule/app-danger-zone-react: the same props and the same DOM for the same input.

Exports <DangerZoneSection> — Card with title/description/button for delete/reset/revoke — and <ConfirmDialog>, the standalone "Are you sure?" modal.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component } from '@angular/core'
import { DangerZoneSection } from '@molecule/app-danger-zone-angular'

@Component({
  selector: 'app-account',
  standalone: true,
  imports: [DangerZoneSection],
  template: `
    <div
      mol-danger-zone-section
      title="Delete account"
      description="This permanently removes your account and all data."
      actionLabel="Delete account"
      (click)="openConfirm()"
    ></div>
  `,
})
export class Account {
  readonly openConfirm = (): void => {
    console.log('open delete-account confirmation')
  }
}

Type

feature

Installation

npm install @molecule/app-danger-zone-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

ConfirmDialogProps

Props accepted by ConfirmDialog — the same props @molecule/app-danger-zone-react accepts. Node-valued props (title, description) are projected content in Angular (an input cannot carry a node), so they are typed unknown; children is the element's default projection. Callbacks use React's names: the component's close/confirm outputs are the same contract.

interface ConfirmDialogProps {
  /** Whether the dialog is open. */
  open: boolean
  /** Called when the dialog should close (escape, backdrop, cancel). */
  onClose?: (event?: unknown) => void
  /** Title (nodes are `[slot=title]` content). */
  title?: unknown
  /** Body / warning text (nodes are `[slot=description]` content). */
  description?: unknown
  /** Confirm-button label (e.g. "Delete"). */
  confirmLabel?: string
  /** Cancel-button label. */
  cancelLabel?: string
  /** Called when the user confirms. */
  onConfirm?: () => void | Promise<void>
  /** Is the confirm action destructive? Defaults to true. */
  destructive?: boolean
  /** Extra body content between description and footer (default projection). */
  children?: unknown
  /** Disables both buttons; the caller owns the pending state. */
  loading?: boolean
}

DangerZoneSectionProps

Props accepted by DangerZoneSection — the same props @molecule/app-danger-zone-react accepts. Node props (title, description, actionLabel, children) are projected content in Angular (an input cannot carry a node), so they are typed unknown: pass them in the host template ([slot=title], [slot=description], [slot=actionLabel] and default content), not as values.

interface DangerZoneSectionProps {
  /** Section title (string/number renders as text; nodes are `[slot=title]` content). */
  title?: unknown
  /** Explanation of the destructive action (nodes are `[slot=description]` content). */
  description?: unknown
  /** Label on the action button (nodes are `[slot=actionLabel]` content). */
  actionLabel?: unknown
  /** Called when the button is clicked; receives the DOM click event. */
  onAction?: (event: MouseEvent) => void
  /** When true, the button disables and shows a loading label. */
  loading?: boolean
  /** When true, the button is disabled without loading. */
  disabled?: boolean
  /** Additional content between description and button (e.g. a confirm-text input), projected as the element's default content. */
  children?: unknown
  /** Extra classes on the Card (the host element). */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string
}

Classes

DangerZoneSection

DangerZoneSection component.

Card-wrapped section for destructive actions — delete account, reset data, revoke access. Uses the error/danger accent color and puts the action on the right. The host IS the Card's <div> (div[mol-danger-zone-section]), matching React's root exactly; the Card classes (cm.card({ variant: 'elevated' }) + cm.cardPadding('md'), the UI Card's defaults) are applied through the host class binding.

The node props are projected slots: title renders inside the <h3>, description inside the <p>, actionLabel inside the action <button>, and children bare between the header and the button row (React renders {children} with no wrapper). String inputs render as text instead — the same values React renders. The action label's capture wrapper detaches while loading is true: React shows the … glyph instead of the label.

@Component({
  selector: 'div[mol-danger-zone-section]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Button],
  inputs: [
    'title',
    'description',
    'actionLabel',
    'loading',
    'disabled',
    'className',
    'dataMolId',
    'onAction',
  ],
  host: {
    '[class]': 'classes()',
    '[attr.data-mol-id]': 'dataMolId ?? null',
  },
  template: `<div [class]="cm().stack(3)">
    <header [class]="cm().stack(1)">
      <h3 [class]="titleClasses()">
        {{ titleText() }}<ng-content select="[slot=title]"></ng-content>
      </h3>
      <p [class]="cm().textSize('sm')">
        {{ descriptionText() }}<ng-content select="[slot=description]"></ng-content>
      </p>
    </header>
    <ng-content></ng-content>
    <div [class]="cm().flex({ justify: 'end' })">
      <button
        mol-button
        [variant]="'solid'"
        [color]="'error'"
        [disabled]="isDisabled()"
        (click)="handleAction($event)"
      >
        {{ loading ? '…' : actionLabelText()
        }}<span #labelSlot><ng-content select="[slot=actionLabel]"></ng-content></span>
      </button>
    </div>
  </div>`,
})
export class DangerZoneSection {
  /** Section title (string/number renders as text; nodes are `[slot=title]` content). */
  title?: unknown
  /** Explanation of the destructive action (string/number as text; nodes are `[slot=description]` content). */
  description?: unknown
  /** Label on the action button (string/number as text; nodes are `[slot=actionLabel]` content). */
  actionLabel?: unknown
  /** When true, the button disables and shows a loading label. */
  loading?: boolean
  /** When true, the button is disabled without loading. */
  disabled?: boolean
  /** Extra classes on the Card. */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string
  /** Called when the button is clicked; receives the DOM click event (React's `onAction`). */
  onAction?: (event: MouseEvent) => void

  /** The action label's capture wrapper (moved out of the DOM once read). */
  @ViewChild('labelSlot') labelSlot?: ElementRef<HTMLSpanElement>

  constructor() {
    usePlacement((hasContent) => this.syncLabels(hasContent))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the Card's class list (`cm.card({ variant: 'elevated' })` +
   * `cm.cardPadding('md')` — the UI Card's defaults — plus `className`).
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().card({ variant: 'elevated' }),
      this.cm().cardPadding('md'),
      this.className,
    )
  }

  /**
   * Computes the title's class (`cm.textSize('base')` + `cm.fontWeight('semibold')`).
   * @returns The class string.
   */
  titleClasses(): string {
    return this.cm().cn(this.cm().textSize('base'), this.cm().fontWeight('semibold'))
  }

  /**
   * The title input's text (React's `{title}` for a text child: strings and
   * numbers render; a node arrives as `[slot=title]` content instead).
   * @returns The text, or `''` for a node title.
   */
  titleText(): string {
    return typeof this.title === 'string' || typeof this.title === 'number'
      ? String(this.title)
      : ''
  }

  /**
   * The description input's text (React's `{description}` for a text child).
   * @returns The text, or `''` for a node description.
   */
  descriptionText(): string {
    return typeof this.description === 'string' || typeof this.description === 'number'
      ? String(this.description)
      : ''
  }

  /**
   * The action label input's text (React's `{actionLabel}` for a text child).
   * @returns The text, or `''` for a node label.
   */
  actionLabelText(): string {
    return typeof this.actionLabel === 'string' || typeof this.actionLabel === 'number'
      ? String(this.actionLabel)
      : ''
  }

  /**
   * The button's disabled state (React's `disabled || loading`; an absent
   * boolean input must not show a disabled button).
   * @returns Whether the button is disabled.
   */
  isDisabled(): boolean {
    return this.disabled === true || this.loading === true
  }

  /** Runs the click handler the way React forwards the DOM event. */
  handleAction(event: MouseEvent): void {
    this.onAction?.(event)
  }

  /**
   * Applies React's label branch: the projected label renders only while
   * there is one and the button is not loading (`{loading ? '…' : actionLabel}`),
   * and it renders BARE — the capture wrapper never shows in the DOM, and the
   * content follows the wrapper's own place.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private syncLabels(hasContent: SlotReader): void {
    const span = this.labelSlot?.nativeElement
    if (!span) return
    if (hasContent(span) && this.loading !== true) {
      // The content stands bare in front of the capture point's place, and the
      // point itself leaves the page: React renders `{actionLabel}` with no wrapper.
      placeContentBefore(span, span)
      setElementPresent(span, false)
      return
    }
    // React shows the `…` glyph instead of the label: the projected nodes go
    // back inside the hidden capture wrapper.
    placeContent(span, null)
    setElementPresent(span, false)
  }
}

ConfirmDialog

ConfirmDialog component.

Composed from Modal and Button exactly as React composes them; the dialog's own title/description/children are projected content ([slot=title], [slot=description], default) or node-valued inputs. React's root is a Modal, which renders a portal while open and nothing while closed, so the host element leaves the page and the portal renders in document.body.

@Component({
  selector: 'mol-confirm-dialog',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Button, Modal, MolTemplateOutlet],
  inputs: ['open', 'title', 'description', 'confirmLabel', 'cancelLabel', 'destructive', 'loading'],
  outputs: ['close', 'confirm'],
  template: `<mol-modal
    #modal
    [open]="open"
    (close)="close.emit($event)"
    [attr.aria-labelledby]="ariaLabelledBy()"
    [attr.aria-describedby]="ariaDescribedBy()"
    ><div [class]="cm().stack(3)">
      <h2
        #titleSlot
        [attr.id]="ariaLabelledBy()"
        [class]="cm().cn(cm().textSize('lg'), cm().fontWeight('bold'))"
      >
        @if (isGiven(title)) {
          <ng-container [molTemplateOutlet]="asTemplate(title)"></ng-container>{{ nodeText(title) }}
        }
        <ng-content select="[slot=title]"></ng-content>
      </h2>
      <p #descriptionSlot [attr.id]="descriptionId" [class]="cm().textSize('sm')">
        @if (isGiven(description)) {
          <ng-container [molTemplateOutlet]="asTemplate(description)"></ng-container
          >{{ nodeText(description) }}
        }
        <ng-content select="[slot=description]"></ng-content>
      </p>
      <ng-content></ng-content>
      <div [class]="cm().flex({ justify: 'end', gap: 'sm' })">
        <button mol-button [variant]="'ghost'" [disabled]="!!loading" (click)="close.emit($event)">
          @if (isGiven(cancelLabel)) {
            <ng-container [molTemplateOutlet]="asTemplate(cancelLabel)"></ng-container
            >{{ nodeText(cancelLabel) }}
          } @else {
            {{ cancelText() }}
          }</button
        ><button
          mol-button
          [variant]="'solid'"
          [color]="destructive === false ? 'primary' : 'error'"
          [disabled]="!!loading"
          (click)="confirm.emit()"
        >
          @if (isGiven(confirmLabel) && !loading) {
            <ng-container [molTemplateOutlet]="asTemplate(confirmLabel)"></ng-container
            >{{ nodeText(confirmLabel) }}
          } @else {
            {{ confirmText() }}
          }
        </button>
      </div>
    </div></mol-modal
  >`,
})
export class ConfirmDialog {
  /**
   * Per-instance id of the rendered title heading, wired as the dialog's
   * accessible name: the binding on `<mol-modal>` reaches the dialog `<div>`,
   * React's `{...rest}` target (Modal names it with `setHostRoot`) —
   * `aria-labelledby` pointing at the visible `<h2>` (WAI-ARIA dialog
   * pattern; axe `aria-dialog-name`).
   */
  readonly titleId = `mol-confirm-dialog-title-${++confirmDialogInstances}`

  /**
   * Per-instance id of the rendered description paragraph, wired as the
   * dialog's accessible description the same way as the title (only bound when projected description content renders — a
   * reference to an empty paragraph describes nothing, axe
   * `aria-dialog-name`/`aria-valid-attr-value`).
   */
  readonly descriptionId = nextInstanceId()

  /** The rendered description paragraph (its projected nodes decide the wiring). */
  // `static: true` resolves the query during creation, so the projected nodes
  // are readable on the FIRST change-detection pass — a non-static query
  // resolves after view init, one pass too late for the description wiring.
  @ViewChild('descriptionSlot', { static: true })
  descriptionSlot?: ElementRef<HTMLParagraphElement>

  /** The title heading (its projected nodes decide whether the dialog points at it). */
  @ViewChild('titleSlot', { static: true }) titleSlot?: ElementRef<HTMLHeadingElement>

  /** Whether the dialog is open. */
  open: ConfirmDialogProps['open'] = false
  /** Title (node-valued prop). */
  title?: ConfirmDialogProps['title']
  /** Body / warning text (node-valued prop). */
  description?: ConfirmDialogProps['description']
  /** Confirm-button label (node-valued prop). */
  confirmLabel?: ConfirmDialogProps['confirmLabel']
  /** Cancel-button label (node-valued prop). */
  cancelLabel?: ConfirmDialogProps['cancelLabel']
  /** Whether the confirm action is destructive (default true). */
  destructive?: ConfirmDialogProps['destructive'] = true
  /** Disables both buttons (the caller owns the pending state). */
  loading?: ConfirmDialogProps['loading']

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText
  /** Whether a node-valued prop was given. */
  readonly isGiven = isGiven

  /** Fires when the dialog should close (escape, backdrop, cancel). */
  @Output() readonly close = new EventEmitter<MouseEvent | undefined>()
  /** Fires when the user confirms. */
  @Output() readonly confirm = new EventEmitter<void>()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The dialog's accessible description id, or null when no description
   * content renders. A signal the template reads, so the association follows
   * the projected description in the pass where it changes.
   */
  readonly ariaDescribedBy = signal<string | null>(null)

  /**
   * The title heading's id, which the dialog's `aria-labelledby` points at, or null while the title
   * renders nothing (React's `slot(title)`): a heading with no text names nothing.
   */
  readonly ariaLabelledBy = signal<string | null>(null)

  /** The composed Modal's element: what the caller binds on this tag lands there, and Modal passes it to its dialog. */
  @ViewChild('modal', { read: ElementRef }) modalElement?: ElementRef<HTMLElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID))

  /**
   * Recomputes `ariaLabelledBy` and `ariaDescribedBy` from the
   * title and description inputs and their projected nodes in
   * the placement function, and takes the host out of the page (React renders
   * the composed `Modal`'s portal in `document.body`, nothing here).
   */
  constructor() {
    usePlacement((hasContent) => {
      this.ariaLabelledBy.set(
        rendersNode(this.title) || hasContent(this.titleSlot?.nativeElement) ? this.titleId : null,
      )
      this.ariaDescribedBy.set(
        rendersNode(this.description) || hasContent(this.descriptionSlot?.nativeElement)
          ? this.descriptionId
          : null,
      )
      setElementPresent(this.host.nativeElement, !this.browser && this.open)
      setHostRoot(this.host.nativeElement, this.modalElement?.nativeElement)
    })
  }

  /**
   * The cancel button's label.
   * @returns The label text.
   */
  cancelText(): string {
    return typeof this.cancelLabel === 'string'
      ? this.cancelLabel
      : this.i18n.t('confirm.cancel', {}, { defaultValue: 'Cancel' })
  }

  /**
   * The confirm button's label when no node label is given (React shows an
   * ellipsis while loading).
   * @returns The label text.
   */
  confirmText(): string {
    if (this.loading) return '…'
    return typeof this.confirmLabel === 'string'
      ? this.confirmLabel
      : this.i18n.t('confirm.confirm', {}, { defaultValue: 'Confirm' })
  }
}

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.13.0 || ^4.0.0
  • @molecule/app-ui ^1.0.1
  • @molecule/app-ui-angular ^1.1.0

Runtime Dependencies

  • @angular/common

  • @angular/core

  • @angular/platform-browser

  • @molecule/app-angular

  • @molecule/app-ui

  • @molecule/app-ui-angular

  • Requires a bonded ClassMap (the Card classes, cm.card + cm.cardPadding('md')) — rendering throws otherwise.

  • Node props are projected content: title, description and actionLabel are selected by [slot=title] / [slot=description] / [slot=actionLabel], everything else lands bare between the header and the button row as the default projection. String inputs render as text.

  • <ConfirmDialog> does NOT track onConfirm's promise and does NOT close itself on confirm: set loading yourself while the action runs, then call onClose() when it settles — otherwise users can double-fire the destructive action or be left staring at an open dialog. Cancel/Confirm fall back to the confirm.* i18n keys (companion bond: @molecule/app-locales-danger-zone); pass confirmLabel/cancelLabel for action-specific wording ("Delete", "Revoke"). destructive (default true) only switches the confirm button color.

Translations

Translation strings are provided by @molecule/app-locales-danger-zone.