@molecule/app-collapsible-section-angular

Feature · collapsible-section · App (browser) · v1.1.5 · Apache-2.0

Expandable section with optional "show more / show less" and count

npm install @molecule/app-collapsible-section-angular

npm · Source on GitHub

How it works

@molecule/app-collapsible-section-angular is a ready-made collapsible-section 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 { CollapsibleSection, ShowMore } from '@molecule/app-collapsible-section-angular'

@Component({
  selector: 'app-faq',
  standalone: true,
  imports: [CollapsibleSection, ShowMore],
  template: `
    <section mol-collapsible-section [title]="'Key concepts'" [defaultExpanded]="true">
      <p>Content revealed when expanded.</p>
    </section>

    <div mol-show-more [initialCount]="3">
      @for (item of items; track item.id) {
        <div>{{ item.label }}</div>
      }
    </div>
  `,
})
export class Faq {
  readonly items = [
    { id: 'a1', label: 'What is Molecule?' },
    { id: 'a2', label: 'How do bonds work?' },
  ]
}

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

Reference

Angular collapsible-section and show-more — the counterpart of @molecule/app-collapsible-section-react: the same props and the same DOM for the same input.

Exports:

  • <CollapsibleSection> — expandable section with a clickable heading.
  • <ShowMore> — "Show N more" / "Show less" toggle for long lists.

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 { CollapsibleSection, ShowMore } from '@molecule/app-collapsible-section-angular'

@Component({
  selector: 'app-faq',
  standalone: true,
  imports: [CollapsibleSection, ShowMore],
  template: `
    <section mol-collapsible-section [title]="'Key concepts'" [defaultExpanded]="true">
      <p>Content revealed when expanded.</p>
    </section>

    <div mol-show-more [initialCount]="3">
      @for (item of items; track item.id) {
        <div>{{ item.label }}</div>
      }
    </div>
  `,
})
export class Faq {
  readonly items = [
    { id: 'a1', label: 'What is Molecule?' },
    { id: 'a2', label: 'How do bonds work?' },
  ]
}

Type

feature

Installation

npm install @molecule/app-collapsible-section-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

CollapsibleSectionProps

Props accepted by the CollapsibleSection component.

interface CollapsibleSectionProps {
  /**
   * Section heading — rendered as an expand-toggle button. Text or a
   * `<ng-template>` ref as the `title` input, or `[slot=title]` content.
   */
  title?: TemplateRef<unknown> | string | null
  /** Body to show when expanded — projected as the element's default content. */
  children?: unknown
  /** Controlled expansion — if omitted, the component owns state. */
  expanded?: boolean
  /** Initial expanded state when uncontrolled. Defaults to false. */
  defaultExpanded?: boolean
  /** Called when expansion state changes. */
  onExpandedChange?: (expanded: boolean) => void
  /** Optional badge / count shown in the header (text, a template ref, or `[slot=badge]`). */
  badge?: TemplateRef<unknown> | string | null
  /** Optional right-side actions (text, a template ref, or `[slot=actions]`). */
  actions?: TemplateRef<unknown> | string | null
  /** Heading level — affects rendered tag, defaults to 3. */
  level?: 2 | 3 | 4 | 5 | 6
  /** Extra classes. */
  className?: string
}

ShowMoreProps

Props accepted by the ShowMore component.

interface ShowMoreProps {
  /** Items before truncation — projected as the element's default content. */
  children?: unknown
  /** Number to show initially. Defaults to 3. */
  initialCount?: number
  /** i18n key for the "Show more" label — receives `{ remaining }`. */
  moreKey?: string
  /** i18n key for the "Show less" label. */
  lessKey?: string
  /** Extra classes. */
  className?: string
}

Classes

CollapsibleSection

CollapsibleSection component.

Expandable section with a clickable heading. Lighter-weight than an accordion — renders a single toggle, not a group of panels. The host IS the root <section> (section[mol-collapsible-section]), matching React's root exactly.

Node props are projected content ([slot=title], [slot=badge], [slot=actions], and the default projection for the body) or template refs on the same-named inputs, as in @molecule/app-announcement-bar-angular. React renders the body <div> only while expanded and the actions <span> only when actions is given; Angular projects into always-mounted capture points, so CollapsibleSection.reconcile detaches and restores those wrappers to match.

@Component({
  selector: 'section[mol-collapsible-section]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [NgTemplateOutlet],
  inputs: [
    'title',
    'badge',
    'actions',
    'expanded',
    'defaultExpanded',
    'onExpandedChange',
    'level',
    'className',
  ],
  host: {
    '[class]': 'classes()',
  },
  template: `@switch (levelTag()) {
      @case (2) {
        <h2><ng-container [ngTemplateOutlet]="headingBody" /></h2>
      }
      @case (4) {
        <h4><ng-container [ngTemplateOutlet]="headingBody" /></h4>
      }
      @case (5) {
        <h5><ng-container [ngTemplateOutlet]="headingBody" /></h5>
      }
      @case (6) {
        <h6><ng-container [ngTemplateOutlet]="headingBody" /></h6>
      }
      @default {
        <h3><ng-container [ngTemplateOutlet]="headingBody" /></h3>
      }
    }
    <div #bodyWrap><ng-content></ng-content></div>
    <ng-template #headingBody>
      <!-- The header row is a container, not a button: a button may not
           contain other controls, and "actions" typically holds them. The
           toggle wraps the label; "actions" sits beside it, so a click there
           never reaches the toggle (no stopPropagation needed). -->
      <span [class]="headerClasses()">
        <button
          type="button"
          (click)="toggle()"
          [attr.aria-expanded]="isOpen() ? 'true' : 'false'"
          [class]="buttonClasses()"
        >
          <span aria-hidden="true">{{ isOpen() ? '▾' : '▸' }}</span>
          <span
            ><ng-content select="[slot=title]"></ng-content>
            @if (titleTemplate(); as titleTpl) {
              <ng-container [ngTemplateOutlet]="titleTpl" />
            } @else if (titleText()) {
              {{ title }}
            }
          </span>
          <ng-content select="[slot=badge]"></ng-content>
          @if (badgeTemplate(); as badgeTpl) {
            <ng-container [ngTemplateOutlet]="badgeTpl" />
          } @else if (badgeText()) {
            {{ badge }}
          }
        </button>
        <span #actionsWrap
          ><ng-content select="[slot=actions]"></ng-content>
          @if (actionTemplate(); as actionTpl) {
            <ng-container [ngTemplateOutlet]="actionTpl" />
          } @else if (actionText()) {
            {{ actions }}
          }
        </span>
      </span>
    </ng-template>`,
})
export class CollapsibleSection implements OnInit {
  /** Section heading — text, a template ref, or `[slot=title]` content. */
  title?: TemplateRef<unknown> | string | null
  /** Optional badge / count — text, a template ref, or `[slot=badge]` content. */
  badge?: TemplateRef<unknown> | string | null
  /** Optional right-side actions — text, a template ref, or `[slot=actions]` content. */
  actions?: TemplateRef<unknown> | string | null
  /** Controlled expansion — when provided, overrides internal state. */
  expanded?: boolean
  /** Initial expanded state when uncontrolled (defaults to false at read time). */
  defaultExpanded?: boolean
  /** Called when expansion state changes (React's `onExpandedChange`). */
  onExpandedChange?: (expanded: boolean) => void
  /** Heading level (defaults to 3 at read time). */
  level?: 2 | 3 | 4 | 5 | 6
  /** Extra classes. */
  className?: string

  /** The body `<div>` (detached while collapsed, as React renders it conditionally). */
  @ViewChild('bodyWrap') bodyWrap?: ElementRef<HTMLElement>
  /** The actions `<span>` (detached when there are no actions). */
  @ViewChild('actionsWrap') actionsWrap?: ElementRef<HTMLElement>

  /** Expansion state while the section is uncontrolled (React's `useState`). */
  private readonly internal = signal(false)
  /** Whether `[slot=actions]` content was projected. */
  private hasActionsSlot = false

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

  /** Reads React's `useState(defaultExpanded)` initial value, once inputs are bound. */
  ngOnInit(): void {
    this.internal.set(this.defaultExpanded ?? false)
  }

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

  /**
   * Computes the root section's class list (React's `cm.cn(cm.stack(2), className)`).
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().stack(2), this.className)
  }

  /**
   * Computes the header row's class list — the container `<span>` that holds
   * the toggle button and the actions (React's old button class list).
   * @returns The class string.
   */
  headerClasses(): string {
    return this.cm().cn(
      this.cm().flex({ align: 'center', justify: 'between', gap: 'sm' }),
      this.cm().w('full'),
      this.cm().sp('py', 2),
      this.cm().textSize('sm'),
      this.cm().fontWeight('semibold'),
    )
  }

  /**
   * Computes the toggle button's class list (React's `cm.flex({ align: 'center', gap: 'sm' })`).
   * @returns The class string.
   */
  buttonClasses(): string {
    return this.cm().flex({ align: 'center', gap: 'sm' })
  }

  /**
   * Whether the section is expanded (React's `expanded ?? internal`).
   * @returns True while expanded.
   */
  isOpen(): boolean {
    return this.expanded ?? this.internal()
  }

  /** The heading level React renders (`h${level}`, default 3). */
  levelTag(): number {
    const level = this.level
    return level === 2 || level === 4 || level === 5 || level === 6 ? level : 3
  }

  /**
   * Toggles expansion state, updating internal state when uncontrolled, and
   * calls `onExpandedChange` with the next state — React's `toggle`.
   */
  toggle(): void {
    const next = !this.isOpen()
    if (this.expanded === undefined) this.internal.set(next)
    this.onExpandedChange?.(next)
  }

  /** The heading as a template, when the caller passed a node. */
  titleTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.title) ? this.title : null
  }

  /**
   * The heading input's text (React renders strings and numbers; a node is projected instead).
   * @returns The text, or `''`.
   */
  titleText(): string {
    return typeof this.title === 'string' || typeof this.title === 'number'
      ? textOf(this.title)
      : ''
  }

  /**
   * The badge as a template, when the caller passed a node.
   * @returns The badge template, or null.
   */
  badgeTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.badge) ? this.badge : null
  }

  /**
   * The badge input's text (React renders strings and numbers; a node is projected instead).
   * @returns The text, or `''`.
   */
  badgeText(): string {
    return typeof this.badge === 'string' || typeof this.badge === 'number'
      ? textOf(this.badge)
      : ''
  }

  /**
   * The actions as a template, when the caller passed a node.
   * @returns The actions template, or null.
   */
  actionTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.actions) ? this.actions : null
  }

  /**
   * The actions input's text (React renders strings and numbers; a node is projected instead).
   * @returns The text, or `''`.
   */
  actionText(): string {
    return typeof this.actions === 'string' || typeof this.actions === 'number'
      ? textOf(this.actions)
      : ''
  }

  /** Whether React's `actions && <span>…` branch renders: the input decides it by its own truthiness when given, the `[slot=actions]` projection otherwise. */
  actionsContent(): boolean {
    if (this.actions !== undefined && this.actions !== null) return Boolean(this.actions)
    return this.hasActionsSlot
  }

  /** Applies React's conditions: the actions `<span>` renders only with actions, the body `<div>` only while expanded. */
  private reconcile(hasContent: SlotReader): void {
    const actions = this.actionsWrap?.nativeElement
    if (actions) this.hasActionsSlot = hasContent(actions)
    setElementPresent(actions, this.actionsContent())
    setElementPresent(this.bodyWrap?.nativeElement, this.isOpen())
  }
}

(The 4 longest member comments are shortened to their first sentence to fit; the full declaration is in node_modules/@molecule/app-collapsible-section-angular/dist/collapsible-section.component.d.ts.)

ShowMore

ShowMore component.

"Show N more" / "Show less" toggle: React truncates its children array with children.slice(0, initialCount). Angular projects the items into the host (div[mol-show-more], matching React's root exactly) and a projected list has no length, so ShowMore.reconcile counts the slot's children whenever they change and takes the ones past initialCount out of the page, each in its own place, putting them back when expanded. The labels come from useTranslation() (showMore.more / showMore.less), read reactively so a locale switch refreshes them.

@Component({
  selector: 'div[mol-show-more]',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: ['initialCount', 'moreKey', 'lessKey', 'className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<span #items><ng-content></ng-content></span>
    @if (remaining() > 0) {
      <button type="button" (click)="toggle()" [class]="buttonClasses()">
        {{ label() }}
      </button>
    }`,
})
export class ShowMore {
  /** Number to show initially (defaults to 3 at read time). */
  initialCount?: number
  /** i18n key for the "Show more" label (defaults to `showMore.more`). */
  moreKey?: string
  /** i18n key for the "Show less" label (defaults to `showMore.less`). */
  lessKey?: string
  /** Extra classes. */
  className?: string

  /** The capture of the items; they render where it stands, directly in the root. */
  @ViewChild('items', { static: true }) private readonly itemsCapture?: ElementRef<HTMLElement>
  /** Reactive translation, read in the injection context. */
  private readonly i18n = useTranslation()
  /** Whether every item shows (React's `expanded`). */
  private readonly expanded = signal(false)
  /** How many items were projected (-1 until measured). */
  private readonly count = signal(-1)
  /** The items this component took out of the page (past `initialCount`). */
  private readonly hidden = new Set<Node>()

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

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

  /**
   * Computes the root div's class list (React's `cm.cn(cm.stack(2), className)`).
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().stack(2), this.className)
  }

  /**
   * Computes the toggle button's class list.
   * @returns The class string.
   */
  buttonClasses(): string {
    return this.cm().cn(this.cm().textSize('sm'), this.cm().fontWeight('semibold'), this.cm().link)
  }

  /**
   * React's `initialCount = 3` default parameter.
   * @returns The initial count.
   */
  initial(): number {
    return this.initialCount ?? 3
  }

  /**
   * How many items the toggle reveals (React's `Math.max(0, children.length - initialCount)`).
   * @returns The remaining count; 0 until the projected items are measured.
   */
  remaining(): number {
    return this.count() < 0 ? 0 : Math.max(0, this.count() - this.initial())
  }

  /**
   * The toggle's label — the "Show N more" text, or "Show less" when expanded.
   * @returns The label text.
   */
  label(): string {
    if (this.expanded())
      return this.i18n.t(this.lessKey ?? 'showMore.less', {}, { defaultValue: 'Show less' })
    const remaining = this.remaining()
    return this.i18n.t(
      this.moreKey ?? 'showMore.more',
      { remaining },
      { defaultValue: `Show ${remaining} more` },
    )
  }

  /** Flips the expanded state (React's `setExpanded((x) => !x)`). */
  toggle(): void {
    this.expanded.set(!this.expanded())
  }

  /**
   * Counts the slot's children (React's `children.length`) and shows the first
   * `initialCount` of them (all of them when expanded), as React's
   * `children.slice(0, initialCount)` renders. An item this component hid is
   * listed by its placeholder, so it is found again through it; items a
   * consumer adds, removes or reorders later are counted the same way.
   *
   * @param hasContent - Reads the slot's children.
   */
  private reconcile(hasContent: SlotReader): void {
    const capture = this.itemsCapture?.nativeElement
    placeContentBefore(capture, capture)
    setElementPresent(capture, false)
    const items = hasContent.nodes(capture).map((node) => {
      const held = heldElement(node)
      return held !== undefined && this.hidden.has(held) ? held : node
    })
    this.count.set(items.length)
    const visible = this.expanded() ? items.length : this.initial()
    this.hidden.clear()
    for (const [index, node] of items.entries()) {
      const shown = index < visible
      setElementPresent(node, shown)
      if (!shown) this.hidden.add(node)
    }
  }
}

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

Node props are projected content: [slot=title], [slot=badge] and [slot=actions] fill the heading, and the element's other content is the body (or, for <ShowMore>, the list items). The same values also work as template refs on the title / badge / actions inputs. <CollapsibleSection> is uncontrolled by default (defaultExpanded); pass expanded to control it — then update it from onExpandedChange. The header renders as a single <button>, so [slot=actions] content must NOT contain buttons/links (nested interactive elements are invalid HTML). <ShowMore>'s labels use the i18n keys showMore.more / showMore.less with English defaultValues; no companion locale bond ships these keys — add them to your app's locale resources (or pass custom moreKey/lessKey). A projected list has no length, so <ShowMore> measures the projected nodes to decide which ones to hide — project the items themselves, not a wrapper around them.