Skip to content

Routed Components ​

A routed component gets its inputs from <ui-view>, which renders it with UIViewInjectedProps: the router, the transition that rendered the view, and the state's resolves. This guide covers three things every routed component meets: reading its state's params, loading its own element module only when the state is entered, and how the page reaches the element a view rendered.

The anatomy of a routed componentthe state declarationthe view renders its componentname: 'user'url: '/users/:id'resolve: [userId]a param, or the element modulecomponent: UserDetaila class, or a template function<ui-view>UIViewInjectedPropsroutertransition that rendered the viewresolves of the stateclass: its _uiViewProps propertytemplate: the function's argumentUserDetail element[routed]routedElement → this elementui-view > [routed] for CSSResolves settle before the state is entered, so the component renders with its inputs ready.

Reading params ​

Declare the params the component needs as a resolve on its state. The resolve depends on $transition$, reads the value once, and hands the component a named, typed input:

ts
import type { Transition } from '@uirouter/core';
import type { LitStateDeclaration } from 'lit-ui-router';

interface UserResolves {
  userId: string;
}

const userState = {
  name: 'user',
  url: '/users/:id',
  resolve: [
    {
      token: 'userId',
      deps: ['$transition$'],
      resolveFn: ($transition$: Transition) => $transition$.params().id,
    },
  ],
  component: UserDetail,
} satisfies LitStateDeclaration<UserResolves>;
ts
import { LitElement, html } from 'lit';
import { property } from 'lit/decorators.js';
import type { UIViewInjectedProps } from 'lit-ui-router';

class UserDetail extends LitElement {
  @property({ attribute: false })
  _uiViewProps?: UIViewInjectedProps<UserResolves>;

  render() {
    return html`<h1>User ${this._uiViewProps?.resolves.userId}</h1>`;
  }
}

The same resolve can fetch the record instead of passing the id through, so the component renders with its data already loaded. The sample app's contacts.contact state (contacts/states.ts) resolves the contact from its contactId param this way.

Reading router.globals.params from the component instead ties it to whatever state is current, not the state it was rendered for, and gives it no type.

A template function can read props.transition.params() directly for a quick view; the RoutedLitTemplate reference shows that form.

Params that change without re-entering the state ​

A non-dynamic param change exits and re-enters the state, so the component is rebuilt with fresh resolves. A dynamic param keeps the component, and its resolves keep the values they had when it was created. Read changed values in uiOnParamsChanged.

Lazy-loading a route's element ​

Importing the element module inside component without awaiting it renders an undefined element that upgrades whenever the chunk arrives, and a failed chunk load surfaces as an unhandled rejection:

ts
component: () => {
  import('./users/users.js'); // not awaited
  return html`<app-users></app-users>`;
},

Await the module in a resolve ​

Return the import from a resolve. Resolves settle before the state is entered, so the element is defined by the time <ui-view> renders it, and a failed import rejects the transition, where transition hooks and stateService.defaultErrorHandler see it:

ts
const usersState = {
  name: 'users',
  url: '/users',
  resolve: [
    {
      token: 'usersElement',
      resolveFn: () => import('./users/users.js'),
    },
  ],
  component: () => html`<app-users></app-users>`,
} satisfies LitStateDeclaration;

The Hello Galaxy tutorial loads @google/model-viewer for one state the same way.

Lazy-load a whole feature with a future state ​

When a feature owns several states, register one placeholder whose name ends in .** and whose lazyLoad imports a module exporting states. The first navigation into the URL prefix loads the module, registers its states in place of the placeholder, and retries the transition:

ts
const contactsFutureState = {
  parent: 'app',
  name: 'contacts.**',
  url: '/contacts',
  lazyLoad: () => import('./contacts/states.js'),
};

The state modules import their components statically, so the elements arrive in the same chunk. The sample app splits contacts, prefs and messages this way (main/states.ts).

The routed element ​

<ui-view> renders into its light DOM, so page CSS and queries reach the routed component. The view's own children are internal: next to the routed markup they hold Lit's part markers and, while one component replaces another, the element on its way out. Reach the routed element through the view instead of firstElementChild or child selectors:

  • routedElement is the element the routed component rendered: a class component's instance, or the first element a template component rendered. It is null while the view shows its fallback content.
  • The same element carries a routed attribute, for CSS.
css
ui-view > [routed] {
  min-height: 100%;
}

A template component marks only its first element. When its template has several top-level elements, wrap them in one element so a [routed] rule reaches all of it.

ts
const view = document.querySelector('ui-view');
view?.routedElement?.scrollIntoView();

When a state change replaces one class component with another, <ui-view> inserts the incoming element next to the outgoing one, and removes the outgoing element once the incoming one has completed its first update. The view keeps its content in between, so a layout read during the swap does not see a collapsed page. Only class-to-class swaps hold the outgoing element: fallback content and template components are replaced in the same update.

routedElement points at the incoming element once the view renders it, and the routed attribute moves to it when that view update commits. Both change before the incoming element has rendered, so during the hold a [routed] rule styles the incoming element, not the outgoing one still on screen.

The hold: how ui-view replaces one routed component with anotherbefore the swapthe view updatesthe incoming elementcompletes its first updateclasscomponent<ui-view>outgoing element[routed]<ui-view>outgoing elementstill on screenincoming element[routed] · not rendered<ui-view>incoming element[routed]routedElement → outgoingroutedElement → incomingroutedElement → incomingthe hold: both stand until the incomingelement has renderedoutgoing element removedtemplatecomponent<ui-view>outgoing element[routed]<ui-view>incoming element[routed]routedElement → outgoingroutedElement → incomingreplaced in the same update: no holdA template component that swaps its own elements without the view updating, as until() does, moves routedElement at once;the routed attribute follows a microtask later.

A template component can also swap its elements without the view updating, as until() does when its content replaces a placeholder. routedElement returns the new first element at once, and the routed attribute follows a microtask later, so code that reads [routed] in the same task as the swap still finds the old element.

The attribute is set when the view renders in the browser, so a prerendered page carries it once its views have hydrated.