@molecule/app-top-nav-layout-angular

Feature · top-nav-layout · App (browser) · v1.2.2 · Apache-2.0

Top navigation app shell: brand link + horizontal NavLinks + UserMenu slot, with a router outlet for nested routes

npm install @molecule/app-top-nav-layout-angular

npm · Source on GitHub

How it works

@molecule/app-top-nav-layout-angular is a ready-made top-nav-layout 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 { TopNavLayout, type TopNavItem } from '@molecule/app-top-nav-layout-angular'

const NAV: TopNavItem[] = [
  { key: 'dashboard', to: '/dashboard', icon: 'dashboard', label: 'Dashboard' },
  { key: 'reports', to: '/reports', icon: 'bar_chart', label: 'Reports' },
]

@Component({
  selector: 'app-shell',
  standalone: true,
  imports: [TopNavLayout],
  template: `
    <div mol-top-nav-layout appName="Acme" [navItems]="nav">
      <button type="button" slot="userMenu">Account</button>
      <router-outlet />
    </div>
  `,
})
export class Shell {
  nav = NAV
}

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

Reference

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

Exports <TopNavLayout> — sticky header with brand link + horizontal router links + a user-menu slot, plus the <main> holding the routed page body (React renders its router's <Outlet /> there) — and the TopNavItem / TopNavLayoutProps types.

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 { TopNavLayout, type TopNavItem } from '@molecule/app-top-nav-layout-angular'

const NAV: TopNavItem[] = [
  { key: 'dashboard', to: '/dashboard', icon: 'dashboard', label: 'Dashboard' },
  { key: 'reports', to: '/reports', icon: 'bar_chart', label: 'Reports' },
]

@Component({
  selector: 'app-shell',
  standalone: true,
  imports: [TopNavLayout],
  template: `
    <div mol-top-nav-layout appName="Acme" [navItems]="nav">
      <button type="button" slot="userMenu">Account</button>
      <router-outlet />
    </div>
  `,
})
export class Shell {
  nav = NAV
}

Type

feature

Installation

npm install @molecule/app-top-nav-layout-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

TopNavItem

A single navigation item rendered in the top nav bar.

interface TopNavItem {
  /** Route path the link goes to. */
  to: string
  /** Stable key — tracks the rendered link and is the i18n key suffix in apps. */
  key: string
  /** Material symbol icon name (or any glyph) shown next to the label. */
  icon?: string
  /** Visible label. Apps that route this through `t(...)` should pass the resolved string. */
  label: string
}

TopNavLayoutProps

Props accepted by TopNavLayout — the same props @molecule/app-top-nav-layout-react accepts. Node props (userMenu, the routed page body) 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.

interface TopNavLayoutProps {
  /** Brand text shown in the top-left link (typically the app name). */
  appName: string
  /** Path the brand link navigates to. Defaults to `'/'`. */
  logoTo?: string
  /** Horizontal nav items rendered in the header. */
  navItems: ReadonlyArray<TopNavItem>
  /** User menu, projected as `[slot=userMenu]` content. */
  userMenu?: unknown
  /**
   * Aria-label for the primary `<nav>`. Overrides the translated /
   * `defaultValue` `'Primary navigation'` (prop > `t()` > default).
   */
  navAriaLabel?: string
  /** Extra classes on the outer wrapper. */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string
  /**
   * The routed page body, projected as the element's default content. React
   * renders its router's `<Outlet />` in the `<main>`.
   */
  children?: unknown
}

Classes

TopNavLayout

TopNavLayout component.

Sticky top-nav shell with brand + horizontal nav + user-menu slot. The host IS the outer <div> (div[mol-top-nav-layout]), matching React's root exactly. The page body is projected as the element's default content; without one the <main> renders <mol-routed-view /> (the matched child route, through whichever routing bond the app wired), and the user menu is projected as [slot=userMenu] content. Nav labels are hidden below the md breakpoint (icon-only mobile nav), so always provide icon names; they render as Material Symbols ligatures and need the Material Symbols font loaded by the host app. Styling comes from the bonded ClassMap. label is rendered as-is: pass an already-translated string.

@Component({
  selector: 'div[mol-top-nav-layout]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Link, RoutedView],
  inputs: ['appName', 'logoTo', 'navItems', 'navAriaLabel', 'className', 'dataMolId'],
  host: {
    '[class]': 'classes()',
    '[attr.data-mol-id]': 'dataMolId ?? null',
  },
  template: `<header [class]="headerClasses()">
      <div [class]="barClasses()">
        <a [molLink]="logoPath()" [class]="brandClasses()">{{ appName }}</a>
        <nav [class]="navClasses()" [attr.aria-label]="navLabel()">
          @for (item of navItems; track item.key) {
            <a
              [molLink]="item.to"
              [attr.aria-label]="item.label"
              [attr.aria-current]="isActive(item) ? 'page' : null"
              [class]="itemClasses(item)"
            >
              @if (item.icon) {
                <span [class]="iconClasses()" aria-hidden="true">{{ item.icon }}</span>
              }
              <span [class]="labelClasses()">{{ item.label }}</span>
            </a>
          }
        </nav>
        <ng-content select="[slot=userMenu]"></ng-content>
      </div>
    </header>
    <main>
      <span #pageSlot><ng-content></ng-content></span>
      @if (routed()) {
        <mol-routed-view />
      }
    </main>`,
})
export class TopNavLayout implements OnDestroy {
  /** Brand text shown in the top-left link (typically the app name). */
  appName = ''
  /** Path the brand link navigates to (defaults to `'/'` at read time). */
  logoTo?: string
  /** Horizontal nav items rendered in the header. */
  navItems: ReadonlyArray<TopNavItem> = []
  /**
   * Aria-label for the primary `<nav>`. Overrides the translated /
   * `defaultValue` `'Primary navigation'` (prop > `t()` > default).
   */
  navAriaLabel?: string
  /** Extra classes on the outer wrapper. */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string

  /** The page body's projection capture point. */
  @ViewChild('pageSlot') private pageSlot?: ElementRef<HTMLElement>

  /**
   * Whether the `<main>` renders the routed view: no page body was projected. A signal the
   * template reads, so the routed view is created only then (it throws without one).
   */
  readonly routed = signal(false)

  private readonly router = useRouterInstance()

  /** The i18n handle (locale-reactive), read in an injection context. */
  private readonly i18n = useTranslation()

  /** The current location, kept current so active items follow navigation. */
  private readonly location = signal(this.router.getLocation())

  private readonly stop = this.router.subscribe(() => this.location.set(this.router.getLocation()))

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

  /** Stops listening to the router when the component goes away. */
  ngOnDestroy(): void {
    this.stop()
  }

  /**
   * React renders `children ?? <RoutedView />`: the routed view only without a
   * page body.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private reconcile(hasContent: SlotReader): void {
    const page = this.pageSlot?.nativeElement
    if (!page) return
    // React renders the projected page body bare: it stands in the capture point's place
    // and the point itself leaves the page.
    placeContentBefore(page, page)
    setElementPresent(page, false)
    this.routed.set(!hasContent(page))
  }

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

  /**
   * Computes the wrapper class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().minH('screen'), this.cm().topNavLayoutRoot, this.className)
  }

  /**
   * Computes the header class list.
   * @returns The class string.
   */
  headerClasses(): string {
    return this.cm().cn(this.cm().topNavLayoutHeader)
  }

  /**
   * Computes the class list of the inner header bar.
   * @returns The class string.
   */
  barClasses(): string {
    const cm = this.cm()
    return cm.cn(
      cm.maxW('7xl'),
      cm.mxAuto,
      cm.sp('px', 6),
      cm.sp('py', 3),
      cm.flex({ align: 'center', justify: 'between', gap: 'lg' }),
    )
  }

  /**
   * Computes the brand link class list.
   * @returns The class string.
   */
  brandClasses(): string {
    return this.cm().cn(this.cm().textSize('2xl'), this.cm().fontWeight('bold'))
  }

  /**
   * Computes the nav class list.
   * @returns The class string.
   */
  navClasses(): string {
    return this.cm().flex({ align: 'center', gap: 'md' })
  }

  /**
   * Computes the icon span class list.
   * @returns The class string.
   */
  iconClasses(): string {
    return this.cm().iconGlyphFont
  }

  /**
   * Computes the label span class list.
   * @returns The class string.
   */
  labelClasses(): string {
    return this.cm().topNavLayoutNavItemLabel
  }

  /**
   * The brand link destination (React's default parameter: a later-bound write
   * of `undefined` must not erase the `'/'` default).
   * @returns The path.
   */
  logoPath(): string {
    return this.logoTo ?? '/'
  }

  /**
   * The nav region's aria-label: prop > `t()` > default. Read in the template,
   * so a locale switch re-renders it, as React's does.
   * @returns The aria-label.
   */
  navLabel(): string {
    return (
      this.navAriaLabel ??
      this.i18n.t('topNavLayout.aria.primaryNavigation', undefined, {
        defaultValue: 'Primary navigation',
      })
    )
  }

  /**
   * Whether one nav item's link is active at the current location.
   * @param item - The nav item.
   * @returns True when the link renders in its active state.
   */
  isActive(item: TopNavItem): boolean {
    return navItemActive(this.location().pathname, item.to)
  }

  /**
   * Computes the class list of one nav link: the shared nav-item treatment
   * plus the active or idle variant.
   * @param item - The nav item.
   * @returns The class string.
   */
  itemClasses(item: TopNavItem): string {
    const cm = this.cm()
    return cm.cn(
      cm.flex({ align: 'center', gap: 'xs' }),
      cm.sp('px', 3),
      cm.sp('py', 2),
      cm.textSize('sm'),
      cm.fontWeight('medium'),
      cm.topNavLayoutNavItem,
      this.isActive(item)
        ? cm.cn(cm.bgPrimaryContainer, cm.textPrimary)
        : cm.cn(cm.textMuted, cm.topNavLayoutNavItemIdle),
    )
  }
}

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.3.11
  • @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

Use it as a LAYOUT component and project the routed page as the element's default content (Angular's own <router-outlet />); the user menu is projected as [slot=userMenu]. Nav labels are hidden below the md breakpoint (icon-only mobile nav), so always provide icon names; they render as Material Symbols ligatures and need the Material Symbols font loaded by the host app. Styling comes from the bonded ClassMap, so a theme/ClassMap bond is a prerequisite. label is rendered as-is: pass an already-translated string.

Translations

Translation strings are provided by @molecule/app-locales-top-nav-layout.