Skip to content

Navigating Programmatically

Josh Thomas edited this page Jun 5, 2018 · 1 revision

If you are in a routed component ( a component that has been included in a stencil-route) and would like to navigate programmatically you first need to pass the router history in as a Prop to your component. Below is an example of this:

import { RouterHistory } from '@stencil/router';

export class askPage {
  @Prop() history: RouterHistory;
}

You can then use the following methods on the history object to navigate:

// pushing a route (going forwards to a certain route)
this.history.push(`/demos`, {});

// popping a route (going back to a certain route)
this.history.pop('/home', {});

// navigate back as if the user hit the back button in the browser
this.history.goBack();

// navigate forwards as if the user hit the forwards button in the browser
this.history.goForward();

// replace the current nav history and reset to a certain route
this.history.replace('/', {});

// navigate through the history stack by `n` entries
this.history.go(n: number);