Hilla Documentation

The router executes callbacks on each view to check whether the navigation should continue, be postponed or be redirected. You need to implement navigation controllers differently, depending on whether the view is on the client or server side.

Hilla Router Navigation Lifecycle (Client-Side Views)

When returning an element or Web Component in a client view, developer might implement the following lifecycle interfaces:

  • BeforeEnterObserver: the onBeforeEnter(location, commands, router) callback is executed before the outlet container is updated with the new element. At this point, the user can cancel the navigation.

  • AfterEnterObserver: the onAfterEnter(location, commands, router) callback is executed after the new element has been attached to the outlet. The difference between this method and onBeforeEnter() is that, when this method is executed, there is no way to cancel the navigation.

  • BeforeLeaveObserver: the onBeforeLeave(location, commands, router) callback is executed before the previous element is detached. Navigation can be cancelled at this point.

  • AfterLeaveObserver: the onAfterLeave(location, commands, router) callback is executed before the element is removed from the DOM. When this method is executed, there is no way to cancel the navigation. During the execution of the onBeforeEnter() and onBeforeLeave() callbacks, the user can postpone the navigation by returning commands.prevent(). Uniquely in onBeforeEnter(), navigation can be redirected by returning commands.redirect(path).

Note
Lifecycle callbacks are asynchronous.

The following snippets show how to cancel navigation in a Web Component:

import { LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import {
  BeforeEnterObserver,
  PreventAndRedirectCommands,
  Router,
  RouterLocation
} from '@vaadin/router';

@customElement('my-view')
class MyView extends LitElement implements BeforeEnterObserver {
  onBeforeEnter(
      location: RouterLocation,
      commands: PreventAndRedirectCommands,
      router: Router) {
    if (location.pathname === '/cancel') {
      return commands.prevent();
    }
  }
}
import { Router } from '@vaadin/router';

...

export const router = new Router(document.querySelector('#outlet'));
router.setRoutes([
  {
    path: 'view1',
    component: 'my-view',
    action: async () => { await import('./views/my-view'); }
  }
]);

For more information, visit the Hilla Router API documentation.