@molecule/app-routing-angular-router

Provider bond · routing · App (browser) · v1.4.2 · Apache-2.0

Angular Router provider for @molecule/app-routing

npm install @molecule/app-routing-angular-router

npm · Source on GitHub · Implements @molecule/app-routing

How it works

@molecule/app-routing-angular-router is a provider bond on the app (browser) side: it implements the routing core interface (@molecule/app-routing) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

import { bootstrapApplication } from '@angular/platform-browser'
import { provideRouter } from '@angular/router'
import { provideMoleculeRouter } from '@molecule/app-routing-angular-router'

bootstrapApplication(App, {
  providers: [
    provideRouter([
      { path: '', component: HomeComponent },
      { path: 'users/:id', component: UserComponent },
    ]),
    provideMoleculeRouter({ routes: [{ path: '/users/:id', name: 'user' }] }),
  ],
})

Works with: @molecule/app-angular, @molecule/app-bond, @molecule/app-i18n, @molecule/app-routing

Reference

Angular Router provider for @molecule/app-routing.

Implements the framework-neutral molecule Router over the Angular Router, so molecule packages and app code can navigate, read params/query and register guards without importing @angular/router — while Angular keeps owning its own routes, links and guards. Guards, named routes, query/hash helpers and subscriptions come from @molecule/app-routing's createHistoryRouter, so this bond behaves exactly like the other routing bonds and an app can swap routing bonds without noticing.

Wire it once at bootstrap, next to Angular's own router providers. It provides the router to @molecule/app-angular (its ROUTER token, its hooks, and <mol-routed-view />, which renders Angular Router's outlet: in a routed layout, the matched child route):

With HTTP and auth clients bonded, the router provideMoleculeRouter provides replaces the current URL with /login after a credential-free GET receives a 401 and the session is confirmed signed out, as React's BrowserRouter does. location.state.from holds the original location. Set signInPath to use a different sign-in route or pass signInPath: false to opt out.

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 { bootstrapApplication } from '@angular/platform-browser'
import { provideRouter } from '@angular/router'
import { provideMoleculeRouter } from '@molecule/app-routing-angular-router'

bootstrapApplication(App, {
  providers: [
    provideRouter([
      { path: '', component: HomeComponent },
      { path: 'users/:id', component: UserComponent },
    ]),
    provideMoleculeRouter({ routes: [{ path: '/users/:id', name: 'user' }] }),
  ],
})

Outside Angular's injector (no inject(AngularRouter) available), build the adapter directly with createAngularRouter; the exported provider constant is the core browser router fallback (an Angular-backed router needs a booted injector, which an import-time constant cannot have).

useMoleculeRouter, useMoleculeQuery, useMoleculeNavigate and useIsActive are React's routing hooks under React's names: they work inside any Angular application whose injector has Angular's Router (provideRouter(routes), or provideRouter plus provideLocationMocks() for a memory history), with or without provideMoleculeRouter — React's hooks never need their provider either. Call them in an injection context; the two whose answer follows the URL return signals. lazyPage is React's lazyPage under React's name: a route page loaded on demand, replaced at once when the URL moves and showing its own fallback until its code arrives — where loadComponent makes the router hold the previous page. Angular page props are the wrapper's props input. ListRouteNav is React's ListRouteNav as <nav mol-list-route-nav>: every declared list view is one of its own anchors, and the URL selects the active choice. Mount provideMoleculeRouter to bond the adapter for @molecule/app-routing's navigate()/getRouter(), to name routes, or to receive onRouterReady. A router a hook created without a provider stays local, so several of them cannot overwrite the global bond.

A route with parameters? Declare its page with defineRoute and read its parameters with injectRouteParams. The route path is the source of truth for the parameter names (:name; Angular paths have no optional parameters):

import { defineRoute, injectRouteParams } from '@molecule/app-routing-angular-router'

class ShelfPage {
  readonly params = injectRouteParams<'shelves/:shelf'>()
}

const routes = [defineRoute('shelves/:shelf', ShelfPage)]

Type

provider

Installation

npm install @molecule/app-routing-angular-router @angular/common @angular/core @angular/router @molecule/app-angular @molecule/app-bond @molecule/app-i18n @molecule/app-routing

API

Interfaces

LazyPageOptions

Options for lazyPage.

interface LazyPageOptions {
  /**
   * What the page's area shows while its code loads: a standalone component rendered in
   * place of the page. Defaults to nothing.
   *
   * React's `fallback` is a node; an Angular route table is module scope, where a
   * `TemplateRef` cannot be built, so the counterpart is the component that would render
   * that node.
   */
  fallback?: Type<unknown>
}

ListRouteNavItem

A named list view and its navigation label.

interface ListRouteNavItem extends ListRouteSelection {
  /** Translated label, optionally including an icon. */
  label: ListRouteNavLabel
  /** Path parameters for this destination; current route parameters are otherwise retained. */
  params?: RouteParams
  /** Keep the choice visible but prevent navigation. Authorization still belongs in the route. */
  disabled?: boolean
}

ListRouteNavItemState

URL-derived state available to the app's link styling.

interface ListRouteNavItemState<Selection extends string = string> {
  /** The app-owned selection key. */
  selection: Selection
  /** Whether the current URL selects this view. */
  active: boolean
  /** Whether navigation is disabled for this choice. */
  disabled: boolean
}

ListRouteNavContext

What a children template receives: the list result, under $implicit (so a template reads it as let-route) and as route.

interface ListRouteNavContext<Selection extends string = string> {
  /** The resolved list, as React's `children` function receives it. */
  $implicit: ListRouteResult<string, Selection>
  /** The resolved list under a readable name. */
  route: ListRouteResult<string, Selection>
}

ListRouteNavProps

Props for URL-backed list navigation; local content panels use the UI package's Tabs instead.

In Angular these are the component's inputs; aria-label and every other native nav attribute (id, class, data-*) are written on the host element itself, which IS the <nav> — the same attributes React spreads onto its nav.

interface ListRouteNavProps<Selection extends string = string> {
  /** Accessible navigation name, translated by the app; set it on the host `<nav>`. */
  'aria-label': string
  /** Every declared view stays visible on every route; labels and targets share one declaration. */
  selections: Record<Selection, ListRouteNavItem>
  /** Tie-breaker or fallback, with the same meaning as useListRoute's defaultSelection. */
  defaultSelection?: NoInfer<Selection>
  /** Pagination query key to remove on selection, defaulting to page. */
  pageParam?: string
  /** Required for protected selections, with the same readiness rules as useListRoute. */
  auth?: ListRouteAuth
  /** Render links in a list, with optional classes for the list and its items. */
  list?: { className?: string; itemClassName?: string }
  /** App-owned styling, resolved from its class map. */
  linkClassName?: string | ((state: ListRouteNavItemState<Selection>) => string | undefined)
  /**
   * Render the list beside the nav using its exact URL state, including resolved item
   * params. Angular passes a template (`<ng-template let-route>`); it renders after the
   * `<nav>`, as React's fragment does.
   */
  children?: TemplateRef<ListRouteNavContext<Selection>>
}

AngularRouterOptions

Angular Router-specific options: the route definitions the molecule router knows before any Router.registerRoutes call.

interface AngularRouterOptions {
  /**
   * Route definitions for named routes (`Router.navigateTo`,
   * `Router.generatePath`) and for resolving params when the native router
   * has no match. Molecule `RouteDefinition`s are independent of Angular's own
   * route config — apps declare Angular's routes with `provideRouter(routes)` and
   * repeat (only) the ones molecule should know by name here.
   */
  routes?: RouteDefinition[]

  /**
   * Called once with the molecule `Router` this provider bonds.
   *
   * `provideMoleculeRouter` bonds the adapter through `@molecule/app-routing`'s
   * `setRouter` when the application bootstraps, so `navigate()`/`getRouter()` from
   * `@molecule/app-routing` drive the real Angular Router; this callback runs at that
   * same moment, once. A second provider, in a route's `providers`, passes its own callback
   * the router the first one bonded, as React's provider inside another does. The options
   * are read when the provider's injector is created, so changing the callback later calls
   * nothing.
   */
  onRouterReady?: (router: Router) => void

  /**
   * Path to replace the current location with on a signed-out GET 401. Defaults to
   * `/login`; `false` turns the redirect off. Read by `provideMoleculeRouter`.
   */
  signInPath?: string | false
}

UseListRouteResult

What useListRoute returns: each list state field as a signal (the same fields React's result carries as plain values) and the list's link builder and navigation actions. This is the shape @molecule/app-angular's useListRoute returns.

interface UseListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** The current 1-indexed page (malformed and non-positive URL values read as page one). */
  readonly page: Signal<number>
  /** The configured items per page. */
  readonly pageSize: Signal<number>
  /** The zero-indexed item offset for an API request. */
  readonly offset: Signal<number>
  /** The current URL filter values, including values supplied by path parameters. */
  readonly filters: Signal<Record<Filter, string | undefined>>
  /** The matching view, or the configured fallback. */
  readonly selection: Signal<Selection | undefined>
  /** The decoded current path parameters, also usable as API-only filters. */
  readonly params: Signal<RouteParams>
  /** Whether the current view may load; a protected view waits for auth. */
  readonly canLoad: Signal<boolean>
  /** Readiness for the current view; a public view always stays ready. */
  readonly status: Signal<ListRouteResult<Filter, Selection>['status']>
  /** The sign-in destination while a signed-out protected view is being redirected. */
  readonly redirectTo: Signal<string | undefined>
  /**
   * Builds a real link target, preserving the current pathname, unrelated query
   * values and hash.
   *
   * @param change - The page, filter, selection and path-parameter changes.
   * @returns The link target for the change.
   */
  readonly href: (change?: ListRouteChange<Filter, Selection>) => string
  /**
   * Navigates atomically; location state is preserved unless options replace it.
   *
   * @param change - The page, filter, selection and path-parameter changes.
   * @param options - Navigation options.
   */
  readonly navigate: (change: ListRouteChange<Filter, Selection>, options?: NavigateOptions) => void
  /**
   * Changes only the page, retaining the current filters and view.
   *
   * @param page - The target page, starting at one.
   * @param options - Navigation options.
   */
  readonly setPage: (page: number, options?: NavigateOptions) => void
  /**
   * Patches URL filters and returns to page one.
   *
   * @param filters - The filter values to write (`undefined` removes one).
   * @param options - Navigation options.
   */
  readonly setFilters: (
    filters: Partial<Record<Filter, string | undefined>>,
    options?: NavigateOptions,
  ) => void
  /**
   * Selects a configured view at page one, preserving current route parameters.
   *
   * @param selection - The view to select.
   * @param options - Navigation options.
   */
  readonly select: (selection: Selection, options?: NavigateOptions) => void
}

ListRouteFilter

Where a list filter lives in the URL. Path values take precedence over query values.

interface ListRouteFilter {
  /** Query key; defaults to the filter's name when `param` is absent. */
  query?: string
  /** Path parameter supplied by the current route, such as `category` in `/topics/:category`. */
  param?: string
  /** Value returned when neither URL source supplies a value; omitted from generated queries. */
  defaultValue?: string
}

ListRouteSelection

A selectable list view, expressed in the app's own route contract.

interface ListRouteSelection {
  /** Absolute route pattern, for example `/members/:member/saved`. */
  path: string
  /** Query values identifying this view. An undefined value requires the key to be absent. */
  query?: QueryParams
  /** A protected selection never loads before authentication is confirmed. */
  requiresAuth?: boolean
}

ListRouteAuth

Authentication readiness for protected list selections.

interface ListRouteAuth {
  /** The auth client's status. Unavailable is distinct from a signed-out session. */
  status: 'loading' | 'authenticated' | 'unauthenticated' | 'unavailable'
  /** App-owned sign-in URL. A signed-out protected visit replaces history with this URL. */
  redirectTo: string
}

ListRouteOptions

URL-backed list state configuration; it neither invents nor rewrites the app's route contract.

interface ListRouteOptions<Filter extends string = string, Selection extends string = string> {
  /** Fixed number of items per page; defaults to 20. */
  pageSize?: number
  /** Query key for a 1-indexed page; defaults to `page`. Page one omits the key. */
  pageParam?: string
  /** Route pattern for changing path-backed filters when no selections are configured. */
  path?: string
  /** Filters and their URL sources. API-only filters do not belong here. */
  filters?: Record<Filter, ListRouteFilter>
  /** Named views sharing a list. Both path variants and query variants are supported. */
  selections?: Record<Selection, ListRouteSelection>
  /** Tie-breaker when multiple selections match, or fallback when none matches. */
  defaultSelection?: NoInfer<Selection>
  /** Required when a selection is protected. Public views remain public as auth changes. */
  auth?: ListRouteAuth
}

ListRouteChange

A single atomic list navigation. Filter/selection changes reset page unless explicitly supplied.

interface ListRouteChange<Filter extends string = string, Selection extends string = string> {
  /** Target page, starting at one. */
  page?: number
  /** Patch of URL filter values. Undefined removes a query filter. */
  filters?: Partial<Record<Filter, string | undefined>>
  /** Target view, resolved through its configured path and query values. */
  selection?: Selection
  /** Optional path parameter changes, for example when opening a different member's saved view. */
  params?: RouteParams
}

ListRouteResult

List state and navigation, derived directly from the current location.

interface ListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** Current 1-indexed page; malformed and non-positive URL values read as page one. */
  page: number
  /** Configured items per page. */
  pageSize: number
  /** Zero-indexed item offset for an API request. */
  offset: number
  /** Current URL filter values, including values supplied by path parameters. */
  filters: Record<Filter, string | undefined>
  /** Matching view, or the configured fallback. */
  selection: Selection | undefined
  /** Decoded current path parameters, also usable as API-only filters. */
  params: RouteParams
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  canLoad: boolean
  /** Readiness for the current view. A public view always stays ready. */
  status: 'ready' | 'loading' | 'unauthenticated' | 'unavailable'
  /** Sign-in destination while a signed-out protected view is being redirected. */
  redirectTo: string | undefined
  /** Build a real link target, preserving the current pathname, unrelated query values and hash. */
  href: (change?: ListRouteChange<Filter, Selection>) => string
  /** Navigate atomically. Location state is preserved unless options explicitly replace it. */
  navigate: (change: ListRouteChange<Filter, Selection>, options?: NavigateOptions) => void
  /** Change only the page, retaining the current filters and view. */
  setPage: (page: number, options?: NavigateOptions) => void
  /** Patch URL filters and return to page one. */
  setFilters: (
    filters: Partial<Record<Filter, string | undefined>>,
    options?: NavigateOptions,
  ) => void
  /** Select a configured view at page one, preserving current route parameters. */
  select: (selection: Selection, options?: NavigateOptions) => void
}

RouteLocation

Current URL decomposed into pathname, search string, hash, navigation state, and unique key.

interface RouteLocation {
  /**
   * Current pathname.
   */
  pathname: string

  /**
   * Query string (including leading ?).
   */
  search: string

  /**
   * Hash (including leading #).
   */
  hash: string

  /**
   * State data passed with navigation.
   */
  state?: unknown

  /**
   * Unique key for this location.
   */
  key?: string
}

RouteMatch

Result of matching a URL against a route pattern (path, params, query string).

interface RouteMatch<Params extends RouteParams = RouteParams> {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Matched URL pathname.
   */
  pathname: string

  /**
   * Route parameters.
   */
  params: Params

  /**
   * Whether this is an exact match.
   */
  isExact: boolean
}

Options for programmatic navigation (replace vs push, carry state, preserve query/hash).

interface NavigateOptions {
  /**
   * Replace current history entry instead of pushing.
   */
  replace?: boolean

  /**
   * State to pass with navigation.
   */
  state?: unknown

  /**
   * Preserve current query params.
   */
  preserveQuery?: boolean

  /**
   * Preserve current hash.
   */
  preserveHash?: boolean
}

RouteDefinition

Route configuration entry (path pattern, name, auth requirements, roles, children).

interface RouteDefinition {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Route name (for named routes).
   */
  name?: string

  /**
   * Whether the route requires exact matching.
   */
  exact?: boolean

  /**
   * Whether the route requires authentication.
   */
  requiresAuth?: boolean

  /**
   * Required roles/permissions.
   */
  roles?: string[]

  /**
   * Route metadata.
   */
  meta?: Record<string, unknown>

  /**
   * Child routes.
   */
  children?: RouteDefinition[]
}

Router

Client-side router providing navigation, guards, route matching, and history control.

All routing providers must implement this interface.

interface Router {
  /**
   * Returns the current route location (pathname, search, hash, state).
   */
  getLocation(): RouteLocation

  /**
   * Gets the current route params.
   */
  getParams<T extends RouteParams = RouteParams>(): T

  /**
   * Gets the current query params.
   */
  getQuery(): QueryParams

  /**
   * Gets a specific query parameter.
   */
  getQueryParam(key: string): string | undefined

  /**
   * Gets the current hash.
   */
  getHash(): string

  /**
   * Navigates to a path. A path that is only a query or a hash (`'?tab=2'`, `'#top'`) stays on
   * the current page, as React Router's `navigate` does; a hash alone drops the current query.
   */
  navigate(path: string, options?: NavigateOptions): void

  /**
   * Navigates to a named route.
   */
  navigateTo(
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ): void

  /**
   * Goes back in history.
   */
  back(): void

  /**
   * Goes forward in history.
   */
  forward(): void

  /**
   * Goes to a specific point in history.
   */
  go(delta: number): void

  /**
   * Updates the current query params.
   */
  setQuery(params: QueryParams, options?: NavigateOptions): void

  /**
   * Updates a specific query parameter.
   */
  setQueryParam(key: string, value: string | undefined, options?: NavigateOptions): void

  /**
   * Updates the current hash.
   */
  setHash(hash: string, options?: NavigateOptions): void

  /**
   * Checks if a path matches the current location.
   *
   * @returns `true` if the path matches the current route.
   */
  isActive(path: string, exact?: boolean): boolean

  /**
   * Matches a path pattern against a pathname.
   */
  matchPath<Params extends RouteParams = RouteParams>(
    pattern: string,
    pathname: string,
  ): RouteMatch<Params> | null

  /**
   * Generates a URL from a named route.
   */
  generatePath(name: string, params?: RouteParams, query?: QueryParams): string

  /**
   * The `href` an anchor to the in-app `path` carries, as the native router's own link
   * writes it (its base path prefixed, or `#/…` under a hash history), so a middle-click,
   * a new tab or a copied link opens the same page a click does. A `path` that is only a
   * query or a hash (`'?tab=2'`, `'#top'`) is the current page's, as `navigate` reads it
   * and as React Router's `<Link>` writes it: `'#top'` on `/docs?x=1` is `/docs#top`.
   *
   * @param path - Pathname with optional query string and hash, as passed to `navigate`.
   * @returns The `href`.
   */
  createHref(path: string): string

  /**
   * Calls `listener` once after each navigation the router commits, however it started (a
   * link, the back button, `navigate`), with the new location and the navigation action.
   * A router calls it before the browser paints the new page, so a component that renders
   * from a listener (the framework bindings' `useLocation` and `useParams` do) shows the new
   * location in the same paint as the new page. Molecule's router conformance tests check
   * that at every paint.
   *
   * @param listener - Called with the new location and the navigation action.
   * @returns Stops calling `listener`.
   */
  subscribe(listener: RouteChangeListener): () => void

  /**
   * Adds a navigation guard.
   */
  addGuard(guard: NavigationGuard): () => void

  /**
   * Registers route definitions.
   */
  registerRoutes(routes: RouteDefinition[]): void

  /**
   * Gets all registered routes.
   */
  getRoutes(): RouteDefinition[]

  /**
   * Destroys the router.
   */
  destroy(): void
}

RouterConfig (deprecated)

Deprecated: Use BrowserRouterConfig (createBrowserRouter) or MemoryRouterConfig (createMemoryRouter): each takes only the options it acts on.

Configuration options for creating a router instance.

interface RouterConfig {
  /**
   * Router mode.
   */
  mode?: 'history' | 'hash' | 'memory'

  /**
   * Base path.
   */
  basePath?: string

  /**
   * Initial routes.
   */
  routes?: RouteDefinition[]
}

Types

LazyLoadableComponent

Any component lazyPage can load: a standalone Angular component.

React's counterpart is what React.lazy accepts (a module whose default is a component); Angular's is the component class itself, since @angular/router has no lazy and a route's component is the class.

type LazyLoadableComponent = Type<unknown>

ListRouteNavLabel

A choice's label: text, or a template when the app renders an icon beside the name.

React's label is a ReactNode; Angular's counterpart of a node is a TemplateRef (the node-value convention the framework's other components share), so a label is plain text or a template rendered inside the choice's link.

type ListRouteNavLabel = string | number | TemplateRef<unknown>

AngularRouteParamName

The parameter names an Angular route path declares (:name). A path that is not a literal declares any name.

type AngularRouteParamName<Path extends string> = string extends Path
  ? string
  : Exclude<ScanAngularPath<Path>, ''>

AngularRouteParams

The parameters an Angular route path declares. Every value is a string, or undefined when the URL leaves the parameter out.

type AngularRouteParams<Path extends string> = Readonly<{
  [Name in AngularRouteParamName<Path>]: string | undefined
}>

ListRouteOptionsInput

The options useListRoute takes: a plain object, or a signal of one when the app's auth status changes on the same mounted component (a new status re-resolves the list, the way React re-renders useListRoute).

type ListRouteOptionsInput<Filter extends string = string, Selection extends string = string> =
  ListRouteOptions<Filter, Selection> | Signal<ListRouteOptions<Filter, Selection>>

RouteParams

URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).

type RouteParams = Record<string, string>

QueryParams

URL query string parameter map (single values or arrays for repeated keys).

type QueryParams = Record<string, string | string[] | undefined>

GuardResult

Navigation guard result.

type GuardResult = boolean | string | { path: string; replace?: boolean } | void

Navigation guard function invoked before each navigation. Return false to cancel, a string/path to redirect, or void to allow.

type NavigationGuard = (
  to: RouteLocation,
  from: RouteLocation | null,
) => GuardResult | Promise<GuardResult>
  • to — The target route location being navigated to.
  • from — The current route location being navigated away from, or null on initial load.

How a navigation moved through the history: a new entry (push), the current entry replaced (replace), or a move to an existing entry (pop: back, forward, go).

type NavigationAction = 'push' | 'replace' | 'pop'

RouteChangeListener

Callback invoked on each route change with the new location and the navigation action that triggered it.

type RouteChangeListener = (location: RouteLocation, action: NavigationAction) => void

Classes

ListRouteNav

Render every declared list view as a router link. The URL selects the active choice, and selecting any view resets pagination through useListRoute. Native link behavior (new-tab clicks, keyboard activation and history) is preserved. This is a navigation landmark, not an ARIA tablist with local panels. No active-value state or change handler is needed. When children is supplied, its template renders after the navigation landmark. Put loading and empty results in that branch so a pending list never removes the filter controls.

The host element IS the <nav> (attribute selector nav[mol-list-route-nav]), so the app's own attributes — aria-label, id, class — sit on it exactly as React's props do on its nav. The links are this component's OWN anchors: each href is the molecule router's createHref (the href the native router's own link writes, base path and hash history included), and a click goes through followRouterLink, so a modified click, a target other than _self or an external URL is left to the browser. The rendered markup is exactly react-router's ListRouteNav: same elements, attributes and ARIA, and no styles of its own.

Works inside any Angular application whose injector has Angular's Router; no molecule provider is needed. Angular creates the page before its router has matched the URL (React renders only once its router resolved one), so the navigation appears with the router's first navigation. Where React takes nodes and a render function, this port takes a TemplateRef: label may be a template rendered inside the link, and children is a template rendered with the resolved list as its context.

@Component({
  selector: 'nav[mol-list-route-nav]',
  standalone: true,
  imports: [NgTemplateOutlet],
  template: LIST_ROUTE_NAV_TEMPLATE,
})
export class ListRouteNav<Selection extends string = string> {
  private readonly router = useMoleculeRouter()
  private readonly selectionsInput = signal<Record<Selection, ListRouteNavItem> | undefined>(
    undefined,
  )
  private readonly defaultSelectionInput = signal<Selection | undefined>(undefined)
  private readonly pageParamInput = signal<string | undefined>(undefined)
  private readonly authInput = signal<ListRouteAuth | undefined>(undefined)
  private readonly listInput = signal<{ className?: string; itemClassName?: string } | undefined>(
    undefined,
  )
  private readonly linkClassNameInput = signal<
    string | ((state: ListRouteNavItemState<Selection>) => string | undefined) | undefined
  >(undefined)
  // The current route's params, the base every choice's destination is built on, as React
  // reads them from `useParams()` on every render.
  private readonly routeParams = signal<RouteParams>(this.router.getParams())
  // Angular creates the page before its router has matched the URL (React renders only
  // after its router resolved one), so the nav appears with the native router's first
  // navigation; until then a choice's `:params` cannot be resolved and nothing renders.
  private readonly nativeRouter = inject(AngularRouter)
  private readonly matched = signal(this.nativeRouter.navigated)
  private readonly destroyRef = inject(DestroyRef)
  private readonly stopParams = this.router.subscribe(() => {
    this.routeParams.set(this.router.getParams())
    this.matched.set(true)
  })
  // The same declaration drives the list rules and the links: item params are applied to
  // the destination path, and the current route's params fill the rest.
  private readonly options = computed<ListRouteOptions<string, Selection>>(() => {
    const current = this.routeParams()
    const destinations: Record<string, ListRouteNavItem> = {}
    const declared = this.selectionsInput()
    if (declared !== undefined) {
      for (const [selection, item] of selectionEntries(declared)) {
        destinations[selection] = item.params
          ? { ...item, path: generatePath(item.path, { ...current, ...item.params }) }
          : item
      }
    }
    return {
      selections: destinations,
      defaultSelection: this.defaultSelectionInput(),
      pageParam: this.pageParamInput(),
      auth: this.authInput(),
    }
  })
  private readonly listRoute: UseListRouteResult<string, Selection> = useListRoute<
    string,
    Selection
  >(this.options)
  // React's `children` function receives the plain resolved list; the hook's signals are
  // read here so a template renders the same object.
  private readonly result = computed<ListRouteResult<string, Selection>>(() => {
    const list = this.listRoute
    return {
      page: list.page(),
      pageSize: list.pageSize(),
      offset: list.offset(),
      filters: list.filters(),
      selection: list.selection(),
      params: list.params(),
      canLoad: list.canLoad(),
      status: list.status(),
      redirectTo: list.redirectTo(),
      href: list.href,
      navigate: list.navigate,
      setPage: list.setPage,
      setFilters: list.setFilters,
      select: list.select,
    }
  })
  private readonly vcr = inject(ViewContainerRef)
  private readonly childrenContext: ListRouteNavContext<Selection> = {
    $implicit: this.result(),
    route: this.result(),
  }
  private childrenTemplate: TemplateRef<ListRouteNavContext<Selection>> | null = null
  private childrenView?: EmbeddedViewRef<ListRouteNavContext<Selection>>
  private viewReady = false

  /** The declared choices, in declaration order. */
  @Input() set selections(value: Record<Selection, ListRouteNavItem>) {
    this.selectionsInput.set(value)
  }

  /** Tie-breaker when several choices match, or the fallback when none does. */
  @Input() set defaultSelection(value: Selection | undefined) {
    this.defaultSelectionInput.set(value)
  }

  /** The pagination query key to reset on selection, defaulting to `page`. */
  @Input() set pageParam(value: string | undefined) {
    this.pageParamInput.set(value)
  }

  /** Authentication readiness for protected selections. */
  @Input() set auth(value: ListRouteAuth | undefined) {
    this.authInput.set(value)
  }

  /** Render the links in a list, with optional classes for the list and its items. */
  @Input() set list(value: { className?: string; itemClassName?: string } | undefined) {
    this.listInput.set(value)
  }

  /** App-owned link styling: one class, or a function of each choice's URL-derived state. */
  @Input() set linkClassName(
    value: string | ((state: ListRouteNavItemState<Selection>) => string | undefined) | undefined,
  ) {
    this.linkClassNameInput.set(value)
  }

  /** The template rendered after the navigation landmark, with the resolved list as its context (React's `children` render function). */
  @Input() set children(value: TemplateRef<ListRouteNavContext<Selection>> | undefined) {
    const next = value ?? null
    if (next === this.childrenTemplate) return
    this.childrenTemplate = next
    if (this.viewReady) this.renderChildren()
  }

  constructor() {
    this.destroyRef.onDestroy(this.stopParams)
    // React re-renders `children` with the new route; an embedded view's context object is
    // updated in place so its view never has to be rebuilt.
    effect(() => {
      const route = this.result()
      this.childrenContext.$implicit = route
      this.childrenContext.route = route
      // The nav (and its children) appear with the native router's first navigation.
      this.matched()
      this.renderChildren()
      this.childrenView?.markForCheck()
    })
  }

  /** Each declared choice with the attributes it renders, recomputed whenever the URL or a declaration changes. */
  protected readonly choices = computed<RenderedChoice<Selection>[]>(() => {
    const route = this.result()
    const linkClassName = this.linkClassNameInput()
    const itemClassName = this.listInput()?.itemClassName
    const declared = this.selectionsInput()
    if (declared === undefined) return []
    return selectionEntries(declared).map(([selection, item]) => {
      const active = route.selection === selection
      const disabled = item.disabled === true
      const to = disabled ? null : route.href({ selection })
      return {
        selection,
        text: labelText(item.label),
        labelTemplate: labelTemplateOf(item.label),
        disabled,
        className:
          typeof linkClassName === 'function'
            ? linkClassName({ selection, active, disabled })
            : linkClassName,
        state: active ? 'active' : 'inactive',
        molId: `list-route-${selection}`,
        current: active ? 'page' : null,
        href: to === null ? null : this.router.createHref(to),
        to,
        itemClassName,
      }
    })
  })

  /** Whether the choices render inside a `<ul>` / `<li>` list. */
  protected readonly withList: Signal<boolean> = computed(() => this.listInput() !== undefined)

  /** The `<ul>`'s class, when the app renders a list. */
  protected listClassName(): string | undefined {
    return this.listInput()?.className
  }

  protected onChoiceClick(event: MouseEvent, choice: RenderedChoice<Selection>): void {
    if (choice.to === null) return
    followRouterLink(event, choice.to, this.router)
  }

  /** Renders the children template, once the component's own view exists. */
  ngAfterViewInit(): void {
    this.viewReady = true
    this.renderChildren()
  }

  private renderChildren(): void {
    if (!this.viewReady || !this.matched() || this.childrenTemplate === null) {
      this.childrenView?.destroy()
      this.childrenView = undefined
      return
    }
    this.childrenView ??= this.vcr.createEmbeddedView(this.childrenTemplate, this.childrenContext)
  }
}

(Member comments are shortened to their first sentence, and the 2 longest are left out to fit; the full declaration is in node_modules/@molecule/app-routing-angular-router/dist/list-route-nav.d.ts.)

Functions

defineRoute(path, page)

Register a literal Angular Router path and the component that renders it.

Create the route at module scope and add it to the routes passed to provideRouter. Pass the component directly or as { Component }. The declared path may keep the leading slash every other routing bond uses (/shelves/:shelf): it is accepted here and removed for Angular's route table, so one string serves the route, href and ListRouteNav. Angular paths have no optional parameters and no splat. Inside the component, call injectRouteParams with the same path to read its parameters.

Use the returned href for links and post-save navigation. It builds the destination from the same path that mounts the page, with the parameter names that path requires. Pass values from the saved response when identity can change.

function defineRoute<const Path extends string>(
  path: Path,
  page: Type<unknown> | { Component: Type<unknown> },
): Route & {
  path: RouteTablePath<Path>
  href: (...args: LinkArgs<Path>) => string
}
  • path — A route path, with or without a leading slash, including any :name parameters.
  • page — The page component class, or { Component: page }.

Returns: The path for Angular's route table, the component, and a function building a link to it.

injectRouteParams()

Read the parameters a route path declares, as a signal that follows URL changes.

Call it in a field initializer or constructor of the page component, where Angular's injection context is active, and name the same path that defineRoute registered: params = injectRouteParams<'/shelves/:shelf'>(). Values are percent-decoded.

function injectRouteParams<Path extends string>(): Signal<AngularRouteParams<Path>>

Returns: A signal of the declared parameters; a parameter missing from the URL is undefined.

useMoleculeRouter()

Gets the molecule Router inside any Angular application that has Angular's Router. No provideMoleculeRouter is required.

When provideMoleculeRouter is mounted, returns its exact router with its named routes. Otherwise returns ONE molecule router per Angular Router instance for that application's whole life — its location, params and queries follow Angular through every navigation, and subscribe() hears Angular's own links and the back button — without bonding it globally. Mount provideMoleculeRouter for the non-Angular @molecule/app-routing navigate()/getRouter() bond, named routes, or onRouterReady.

Call it in an injection context (a component field initializer or constructor).

function useMoleculeRouter(): Router

Returns: The molecule Router instance.

useMoleculeNavigate()

Gets a navigate function with the molecule Router options inside any Angular application that has Angular's Router. provideMoleculeRouter is optional; mount it only for named routes, the non-Angular navigate()/getRouter() bond, or onRouterReady.

Call it in an injection context (a component field initializer or constructor).

function useMoleculeNavigate(): Router['navigate']

Returns: The navigate function, bound to the router the hook resolved.

useMoleculeQuery()

Gets the current query parameters as a signal inside any Angular application that has Angular's Router, re-evaluated on every navigation. provideMoleculeRouter is optional; mount it only for named routes, the non-Angular navigate()/getRouter() bond, or onRouterReady.

Call it in an injection context (a component field initializer or constructor).

function useMoleculeQuery(): Signal<QueryParams>

Returns: A signal of the query parameters; read it in the template as query().

useIsActive(path, exact)

Checks whether a path is currently active inside any Angular application that has Angular's Router, re-evaluated on every navigation. provideMoleculeRouter is optional; mount it only for named routes, the non-Angular navigate()/getRouter() bond, or onRouterReady.

Call it in an injection context (a component field initializer or constructor).

function useIsActive(path: string, exact?: boolean): Signal<boolean>
  • path — The path to check.
  • exact — Whether to require an exact match (default: false).

Returns: A signal of whether the path is active; read it in the template as active().

lazyPage(load, options)

Load a route's page on demand, inside the page's own area.

Use it instead of Angular's loadComponent for every page a route renders. Navigating to a page whose code has not loaded yet then replaces the previous page at once: the previous page leaves and this component's own fallback shows in the page's area until its code arrives. With loadComponent, @angular/router awaits the code after guards and resolvers and before activating the route, so a navigation the URL has already moved for — the Back button, which the browser has already applied, or any route with urlUpdateStrategy: 'eager' — keeps the previous page in the DOM under the new URL, and a check such as getByRole('heading') finds the old page's headings. Layout routes (an app shell around <router-outlet>) stay mounted either way.

The page's props are this component's props input, a record of the page's inputs, which are bound onto the loaded component through NgComponentOutlet. Most pages read their route parameters with injectRouteParams and take no props at all.

function lazyPage<Page extends LazyLoadableComponent>(
  load: () => Promise<{ default: Page }>,
  options?: LazyPageOptions,
): Type<{ props: LazyPageProps<Page> }>
  • load — Loads the page module, as import() does: () => import('./pages/Article.js').then((m) => ({ default: m.Article })).
  • options — Optional fallback component shown in the page's area while its code loads.

Returns: The component to use as a route's component: { path: 'article/:slug', component: Article }. Its single input, props, takes the page's own props.

createAngularRouter(router, location, options)

Creates a molecule Router over the Angular Router.

Reads, navigation and notifications all go through Angular itself: location() parses router.url, push/replace call router.navigateByUrl (returning its promise), go calls location.historyGo, and listen follows router.events — one notification per committed navigation (Angular's own links, the back button, or this router's navigate), 'pop' for a popstate navigation, nothing for a cancelled, failed or skipped one. Each committed entry gets a location key in its history.state, which Angular carries through Back and Forward, so the key names the entry as React Router's does. Guards, named routes and the query/hash helpers come from createHistoryRouter.

function createAngularRouter(
  router: AngularRouter,
  location: Location,
  options?: AngularRouterOptions,
): Router
  • router — Angular's Router (inject it, or get it from an EnvironmentInjector).
  • location — Angular's Location over the same history (injected alongside the router; with provideRouter it shares the LocationStrategy the router uses).
  • options — Molecule route definitions for named routes and route params.

Returns: A molecule Router driving the Angular Router.

provideMoleculeRouter(options)

Provides the molecule Router built on Angular's own Router and Location, through @molecule/app-angular's provideRouter, so molecule packages and app code (inject(ROUTER), @molecule/app-angular's hooks and services) navigate through Angular, and <mol-routed-view /> renders Angular Router's outlet: in a routed layout, the matched child route.

Apps add it next to Angular's own provideRouter(routes) — Angular keeps owning its route config; the molecule options only name the routes molecule should know (Router.navigateTo, Router.generatePath).

The application's environment initializer bonds the adapter through @molecule/app-routing's setRouter when the app bootstraps (React's MoleculeRouterProvider bonds in its mount effect), so navigate()/getRouter() from @molecule/app-routing drive the real Angular Router instead of the core's browser-history fallback. AngularRouterOptions.onRouterReady runs at that same moment, once for each provideMoleculeRouter: a second one, in a route's providers, uses the router already built for that Angular Router, adds its routes to it, and passes it to its own callback, as React's provider inside another does.

With HTTP and auth clients bonded, the router replaces the current location with /login after a credential-free GET receives a 401 and the session is confirmed signed out, as React's BrowserRouter does (redirectSignedOutRejections from @molecule/app-routing), until the application is destroyed. location.state.from holds the original location. Set signInPath to use a different sign-in route or signInPath: false to opt out.

function provideMoleculeRouter(options?: AngularRouterOptions): EnvironmentProviders
  • options — Molecule route definitions for named routes and route params, and the optional ready callback.

Returns: Environment providers.

useConsumedSearchParam(name)

Consume a credential query parameter into component state and remove only that parameter from the address through the Angular Router. The value survives local rerenders, failed-submit retries and later query-only navigation; a newly arriving value on the same mounted route is consumed too. Path, hash, unrelated query values and router location state are retained.

The bond's router owns the URL replacement, so the Angular Router's location and window.location agree. Its replace keeps the entry's app-owned state fields, including ones Angular Router does not model: the bond reads every non-Angular key into the location's state and carries it back on the replace (React Router drops those keys, which is why React's hook re-adds them itself).

Call it in an injection context (a component field initializer or constructor).

function useConsumedSearchParam(name: string): readonly [string, (value: string) => void]
  • name — The credential query key to consume, for example token or code.

Returns: The consumed value and its setter, in the same tuple shape @molecule/app-angular's useConsumedSearchParam returns: index 0 is the value ('' before first consumption, kept current in place) and index 1 sets it.

useListRoute(options)

Own URL-backed pagination, filters and selected views without mirrored state or navigation effects. Works inside any Angular application whose injector has Angular's Router (provideRouter(routes), or provideRouter plus provideLocationMocks() for a memory history); no molecule provider is needed. Ordinary links, direct visits and Back/Forward all read the same URL. Page links retain path parameters and unrelated queries; changing filters or views resets the page atomically. Protected views wait for auth and redirect only a confirmed signed-out session, with state.returnTo set.

Call it in an injection context (a component field initializer or constructor). The options may be a signal: an auth status going from loading to unauthenticated reaches the list on the same component, the way React re-renders useListRoute with new options.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: ListRouteOptionsInput<Filter, Selection>,
): UseListRouteResult<Filter, Selection>
  • options — App-owned filter sources, view paths, pagination and optional auth readiness (or a signal of them).

Returns: Reactive list state as signals, plus link builders and navigation actions. Gate data queries with canLoad.

parseSearchParams(searchParams)

Converts URLSearchParams into QueryParams. A key that appears more than once becomes an array of its values, in order.

function parseSearchParams(searchParams: URLSearchParams): QueryParams
  • searchParams — The search params to read.

Returns: The query params.

stringifyQuery(params)

Serializes QueryParams into a query string with a leading ?, percent-encoding keys and values (a space is %20). Undefined values are left out; an array writes its key once per value.

function stringifyQuery(params: QueryParams): string
  • params — The query params.

Returns: The query string, or '' when there is nothing to write.

matchPath(pattern, pathname, exact)

Matches a route pattern against a pathname. :name captures one segment and * matches anything. The whole pathname must match unless exact is false, which also accepts a pathname that only starts with the pattern.

function matchPath<Params extends RouteParams = RouteParams>(
  pattern: string,
  pathname: string,
  exact?: boolean,
): RouteMatch<Params> | null
  • pattern — The pattern, such as /users/:id or /files/*.
  • pathname — The pathname to match.
  • exact — Whether the whole pathname must match (default true).

Returns: The match with its params, or null.

generatePath(pattern, params)

Builds a path from a pattern by putting each :name param in its place, percent-encoded. A pattern given no params is returned as it is.

function generatePath(pattern: string, params?: RouteParams): string
  • pattern — The pattern, such as /users/:id.
  • params — The param values.

Returns: The path.

resolvePath(to, fromPathname)

Resolves a path against the pathname it is relative to: an absolute to is returned as it is; otherwise to is joined to fromPathname's parent, with .. moving up and . staying.

function resolvePath(to: string, fromPathname: string): string
  • to — The path to resolve.
  • fromPathname — The pathname it is relative to.

Returns: The resolved pathname.

normalizePath(path)

Removes trailing slashes from a path, keeping / itself.

function normalizePath(path: string): string
  • path — The path.

Returns: The path without trailing slashes.

Constants

provider

The conventional typed provider constant.

The Angular Router only exists inside a booted injector (inject(AngularRouter), inject(Location)), so this constant — resolved at import time, before any app boots — cannot be Angular-backed: it is the core @molecule/app-routing createBrowserRouter (same Router interface, plain browser history). Angular apps should NOT wire it; use provideMoleculeRouter next to provideRouter(routes) to get the Angular-backed router.

const provider: Router

Core Interface

Implements @molecule/app-routing interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setRouter } from '@molecule/app-routing'
import { provider } from '@molecule/app-routing-angular-router'

export function setupRoutingAngularRouter(): void {
  setRouter(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/router ^22.0.0
  • @molecule/app-angular ^3.13.0 || ^4.0.0
  • @molecule/app-bond ^1.0.1
  • @molecule/app-i18n ^1.0.1
  • @molecule/app-routing ^1.5.0

Runtime Dependencies

  • @angular/common
  • @angular/core
  • @angular/router
  • @molecule/app-angular
  • @molecule/app-bond
  • @molecule/app-i18n
  • @molecule/app-routing