@molecule/app-header-angular

Feature · header · App (browser) · v1.2.3 · Apache-2.0

Top app-shell header: branded logo + appName on the left, slotted actions (theme toggle, user menu, extras) on the right

npm install @molecule/app-header-angular

npm · Source on GitHub

How it works

@molecule/app-header-angular is a ready-made header 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 { AppHeader } from '@molecule/app-header-angular'

@Component({
  selector: 'app-shell',
  standalone: true,
  imports: [AppHeader],
  template: `
    <!-- UserMenu takes its settings panel as projected content; the panel
         dismisses the drawer via usePanelClose(). -->
    <header mol-app-header [appName]="'Bearing'">
      <app-user-menu slot="userMenu">
        <div>Your settings panel here</div>
      </app-user-menu>
    </header>
  `,
})
export class Shell {}

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

Reference

Angular top app-shell header — the counterpart of @molecule/app-header-react: the same props and the same DOM for the same input.

Branded logo + appName on the left, slotted actions (theme toggle, extra actions, user menu) on the right. Pair with @molecule/app-shell-layout-angular's AppShellLayout to assemble a full chrome.

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 { AppHeader } from '@molecule/app-header-angular'

@Component({
  selector: 'app-shell',
  standalone: true,
  imports: [AppHeader],
  template: `
    <!-- UserMenu takes its settings panel as projected content; the panel
         dismisses the drawer via usePanelClose(). -->
    <header mol-app-header [appName]="'Bearing'">
      <app-user-menu slot="userMenu">
        <div>Your settings panel here</div>
      </app-user-menu>
    </header>
  `,
})
export class Shell {}

Type

feature

Installation

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

API

Interfaces

AppHeaderNavigation

A primary navigation landmark with one link per declared destination — the Angular form of @molecule/app-header-react's navigation prop.

interface AppHeaderNavigation {
  /** Accessible name for the navigation landmark. */
  label: string
  /** Router destinations mapped to their link props, the destination itself being the key. */
  links: Readonly<Record<string, AppHeaderNavigationLink | undefined>>
  /** Additional class on the native nav element. */
  className?: string
  /** Additional class on the links' list. */
  listClassName?: string
  /** Additional class on each list item. */
  itemClassName?: string
}

AppHeaderProps

Props for AppHeader — the same props @molecule/app-header-react accepts. Node props (userMenu, themeToggle, extraActions) are projected content in Angular (an input cannot carry a node), so they are typed unknown: pass them in the host template, not as values. The one value themeToggle still accepts is null, which force-hides the default toggle exactly like React's themeToggle={null}.

interface AppHeaderProps {
  /** Brand display name shown next to the logo. */
  appName: string
  /** Logo image source. Defaults to `/logo.svg` (the convention scaffolded by mlcl). */
  logoSrc?: string
  /** Logo size in pixels (square). Defaults to 30 to match the flagship-app convention. */
  logoSize?: number
  /** Path the brand link navigates to. Defaults to `/`. */
  brandTo?: string
  /** Additional class on the brand anchor. */
  brandClassName?: string
  /**
   * Primary destinations, rendered inside the navigation landmark that
   * wraps the header's brand and actions (React's `navigation`). Without it
   * the header keeps a plain brand-and-actions wrapper with no `<nav>`.
   */
  navigation?: AppHeaderNavigation
  /** Slot for the right-side user menu, projected as `[slot=userMenu]` content. */
  userMenu?: unknown
  /**
   * Theme toggle slot. The DEFAULT toggle renders only when BOTH the theme
   * provider and the i18n provider are provided above the header (probed
   * through `inject(THEME_PROVIDER/I18N_PROVIDER, { optional: true })`, the
   * non-throwing probe of React's `useContext`); otherwise it is silently
   * omitted. Pass your own component (projected as `[slot=themeToggle]`
   * content) to override it, or bind the `themeToggle` input to `null` to
   * force-hide it.
   */
  themeToggle?: unknown | null
  /** Optional extra actions rendered between the theme toggle and the user menu, projected as `[slot=extraActions]` content. */
  extraActions?: unknown
  /**
   * Apply `cm.headerFixed` for sticky/fixed positioning. Defaults to `true`,
   * matching the flagship-app convention. Set to `false` for a non-sticky header.
   */
  fixed?: boolean
  /** Extra className on the outer `<header>` (composed with `cm.headerBar` + optional `cm.headerFixed`). */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string
}

Classes

AppHeader

AppHeader component.

Sticky top app-shell header — logo + appName on the left, slotted actions on the right. The host IS the <header> (header[mol-app-header]), matching React's root exactly. All visual styling routes through ClassMap tokens (cm.headerBar, cm.headerFixed, cm.headerInner, cm.logoText) so the bonded styling layer controls the visual treatment.

The brand link is the binding's Link (<a molLink>), react-router's <Link to> contract. When navigation is set, the inner wrapper becomes the navigation landmark (<nav aria-label>) holding the brand, the declared links and the action slots — React's navigation prop; without it the wrapper stays a plain <div> and the header has no landmark. The three action slots are projected content ([slot=themeToggle], [slot=extraActions], [slot=userMenu]); React renders them bare, so each capture span moves its projected nodes to the slot's position and leaves the DOM. When the themeToggle slot is empty and the themeToggle input is not null, the resilient default renders — the UI package's ThemeToggle, but ONLY when both the theme provider and the i18n provider are provided above the header (probed with inject(TOKEN, { optional: true }), which never throws), exactly like React's DefaultThemeToggle context probe.

@Component({
  selector: 'header[mol-app-header]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Flex, Link, NavLinkAttributes, NgTemplateOutlet, ThemeToggle],
  inputs: [
    'appName',
    'logoSrc',
    'logoSize',
    'brandTo',
    'brandClassName',
    'navigation',
    'themeToggle',
    'fixed',
    'className',
    'dataMolId',
  ],
  host: {
    '[class]': 'headerClasses()',
    '[attr.data-mol-id]': 'dataMolId ?? null',
  },
  // prettier-ignore
  template: `@if (navigation; as nav) {
      <nav [class]="innerClasses()" [attr.aria-label]="nav.label">
        <ng-container [ngTemplateOutlet]="inner" />
      </nav>
    } @else {
      <div [class]="innerClasses()">
        <ng-container [ngTemplateOutlet]="inner" />
      </div>
    }
    <ng-template #inner>
      <div mol-flex [align]="'center'" [justify]="'between'" [className]="cm().h('full')">
        <a [class]="brandClassName" [molLink]="brandToValue()">
          <div mol-flex [align]="'center'" [gap]="'xs'">
            <img
              alt=""
              [attr.src]="logoSrcValue()"
              [attr.width]="logoSizeValue()"
              [attr.height]="logoSizeValue()"
            />
            <span [class]="logoTextClasses()">{{ appName }}</span>
          </div>
        </a>
        <div mol-flex [align]="'center'" [gap]="'sm'">
          @if (navigation; as nav) {
            <ul [class]="nav.listClassName">
              @for (entry of navigationLinks(); track entry.to) {
                <li [class]="nav.itemClassName">
                  <a [molLink]="entry.to" [replace]="entry.link.replace" [state]="entry.link.state" [molNavLinkAttrs]="entry.link" (click)="handleLinkClick(entry.link, $event)">@if (templateOf(entry.link.children); as content) {<ng-container [ngTemplateOutlet]="content"></ng-container>}@else {{{ textOf(entry.link.children) }}}</a>
                </li>
              }
            </ul>
          }
          <span data-mol-slot="themeToggle"
            ><ng-content select="[slot=themeToggle]"></ng-content
          ></span>
          @if (showDefaultToggle()) {
            <button mol-theme-toggle></button>
          }
          <span data-mol-slot="extraActions"
            ><ng-content select="[slot=extraActions]"></ng-content
          ></span>
          <span data-mol-slot="userMenu"><ng-content select="[slot=userMenu]"></ng-content></span>
        </div>
      </div>
    </ng-template>`,
})
export class AppHeader {
  /** Brand display name shown next to the logo. */
  appName = ''
  /** Logo image source (defaults to `/logo.svg` at read time). */
  logoSrc?: string
  /** Logo size in pixels (square; defaults to 30 at read time). */
  logoSize?: number
  /** Path the brand link navigates to (defaults to `/` at read time). */
  brandTo?: string
  /** Additional class on the brand anchor. */
  brandClassName?: string
  navigation?: AppHeaderNavigation
  /** Force-hides the default theme toggle when bound to `null` (React's `themeToggle={null}`). */
  themeToggle?: null
  /** Apply `cm.headerFixed` (defaults to `true` at read time). */
  fixed?: boolean
  /** Extra className on the outer `<header>`. */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string

  /** The header host element — the app's projected nodes live inside it. */
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef)

  /** The theme provider above the header, or null — React's `useContext(ThemeContext)` probe. */
  private readonly themeProvider = inject(THEME_PROVIDER, { optional: true })

  /** The i18n provider above the header, or null — React's `useContext(I18nContext)` probe. */
  private readonly i18nProvider = inject(I18N_PROVIDER, { optional: true })

  /** Whether each slot carries projected nodes (drives the default toggle's `@if`). */
  private readonly slots = signal({ toggle: false, extra: false, menu: false })

  /** The rendered capture spans, kept once a span leaves the DOM so content that arrives later is still read and placed. */
  private readonly spans = new Map<string, HTMLSpanElement>()

  constructor() {
    // The placement runs after a navigation change recreates the outlet view
    // (and its capture spans), so the slots are re-established then too.
    usePlacement((hasContent) => this.syncSlots(hasContent))
  }

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

  /** Computes the header class list (`cm.headerBar` + optional `cm.headerFixed` + `className`). */
  headerClasses(): string {
    return this.cm().cn(
      this.cm().headerBar,
      this.isFixed() ? this.cm().headerFixed : '',
      this.className,
    )
  }

  innerClasses(): string {
    const navigation = this.navigation
    return navigation?.className
      ? this.cm().cn(this.cm().headerInner, navigation.className)
      : this.cm().cn(this.cm().headerInner)
  }

  navigationLinks(): NavLinkEntry[] {
    return Object.entries(this.navigation?.links ?? {}).flatMap(([to, link]) =>
      link ? [{ to, link }] : [],
    )
  }

  handleLinkClick(link: NavLinkEntry['link'], event: MouseEvent): void {
    const handler = link.onClick
    if (typeof handler === 'function') handler(event)
  }

  /** Narrows a link's content to an embedded template (React's node child). */
  templateOf(value: unknown): TemplateRef<unknown> | null {
    return asTemplate(value)
  }

  /** Renders text content — React renders a string or a number as text. */
  textOf(value: unknown): string {
    return nodeText(value)
  }

  /** The brand text's class (`cm.logoText`), through `cn()` so a token that is a function in the bonded map resolves to its string. */
  logoTextClasses(): string {
    return this.cm().cn(this.cm().logoText)
  }

  /** Whether the header is fixed (React's `fixed` default parameter). */
  isFixed(): boolean {
    return this.fixed ?? true
  }

  /** The logo image source (React's default parameter). */
  logoSrcValue(): string {
    return this.logoSrc ?? '/logo.svg'
  }

  /** The logo pixel size (React's default parameter). */
  logoSizeValue(): number {
    return this.logoSize ?? 30
  }

  /** The brand link target (React's default parameter). */
  brandToValue(): string {
    return this.brandTo ?? '/'
  }

  showDefaultToggle(): boolean {
    return (
      !this.slots().toggle &&
      this.themeToggle !== null &&
      !!this.themeProvider &&
      !!this.i18nProvider
    )
  }

  /** Places every slot's projected content at its position and records which slots carry content. */
  private syncSlots(hasContent: SlotReader): void {
    const spans = this.captureSpans()
    if (spans.size === 0) return
    const toggle = spans.get('themeToggle')
    const extra = spans.get('extraActions')
    const menu = spans.get('userMenu')
    // Read presence BEFORE relocating: the placement moves the projected nodes out.
    const state = {
      toggle: toggle ? hasContent(toggle) : false,
      extra: extra ? hasContent(extra) : false,
      menu: menu ? hasContent(menu) : false,
    }
    for (const span of [toggle, extra, menu]) {
      if (span) this.relocate(span)
    }
    const current = this.slots()
    if (
      current.toggle !== state.toggle ||
      current.extra !== state.extra ||
      current.menu !== state.menu
    ) {
      this.slots.set(state)
    }
  }

  /** The rendered capture spans, keyed by slot name, merged with the spans kept from earlier renders. */
  private captureSpans(): Map<string, HTMLSpanElement> {
    for (const el of Array.from(
      this.host.nativeElement.querySelectorAll<HTMLSpanElement>('span[data-mol-slot]'),
    )) {
      const slot = el.getAttribute('data-mol-slot')
      if (slot) this.spans.set(slot, el)
    }
    return this.spans
  }

  private relocate(span: HTMLSpanElement): void {
    placeContentBefore(span, span)
    setElementPresent(span, false)
  }
}

(Member comments are shortened to their first sentence, and the 6 longest are left out to fit; the full declaration is in node_modules/@molecule/app-header-angular/dist/app-header.component.d.ts.)

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.3.0

Runtime Dependencies

  • @angular/common

  • @angular/core

  • @angular/platform-browser

  • @molecule/app-angular

  • @molecule/app-ui

  • @molecule/app-ui-angular

  • Must render inside the binding's router (provideRouter) — the brand link is the binding's Link (<a molLink>, react-router's <Link> contract), which throws outside one.

  • The DEFAULT themeToggle slot renders <button mol-theme-toggle> (which calls useTheme() + useTranslation()) ONLY when BOTH the theme provider and the i18n provider are provided above the header — it probes them with inject(THEME_PROVIDER/I18N_PROVIDER, { optional: true }), which never throws. Without those providers the toggle is silently OMITTED instead of throwing, so <header mol-app-header> renders out of the box; it lights up automatically once they are wired. Bind the themeToggle input to null to force-hide it, or project your own [slot=themeToggle] content to override.

  • fixed defaults to true (cm.headerFixed positions the header fixed): give the page content a matching top offset (flagships get it from AppShellLayout), or pass fixed=false for an in-flow header.

  • logoSrc defaults to /logo.svg, the file mlcl scaffolds into public/.

  • Styling routes through ClassMap tokens (cm.headerBar, cm.headerFixed, cm.headerInner, cm.logoText) — requires a bonded ClassMap.