Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Routing and Templates

Links, Navigation and the Router Service

Navigate in Ember with LinkTo, pass models and ids to dynamic routes, style active links, and move programmatically with the router service - transitionTo, replaceWith and urlFor.

Users move around an Ember app in two ways: by clicking links, and by something happening in code, such as a form that saves and then shows the new record. Ember has one tool for each: the LinkTo component for templates and the router service for JavaScript. Both work with route names, never raw URLs.

Real versus stand-in. The LinkTo and router service code is real and read-only. The runnable blocks are plain JavaScript stand-ins that mimic URL generation and navigation history so you can see what the framework does for you.

LinkTo

Import LinkTo from @ember/routing and give it a route name:

JavaScript
// app/templates/application.gjs
import { LinkTo } from '@ember/routing';

<template>
  <nav>
    <LinkTo @route="index">Home</LinkTo>
    <LinkTo @route="posts">Posts</LinkTo>
    <LinkTo @route="posts.new" class="button">Write a post</LinkTo>
  </nav>
  {{outlet}}
</template>

It renders a normal <a href="...">, so open-in-new-tab, copy-link and accessibility all work. A normal click is intercepted and handled by the router without reloading the page. Extra attributes such as class are forwarded to the <a> element.

LinkTo adds the class active when its route is the current one or one of its parents. So a link to posts stays highlighted while you view posts.post. Style it:

CSS
nav a.active {
  font-weight: bold;
  text-decoration: underline;
}

If you need different highlighting logic, the router service's isActive method (below) can compute it.

Dynamic segments

For a route with a dynamic segment you must tell LinkTo what to fill in. Pass the value as @model (or with several segments, @models):

JavaScript
import { LinkTo } from '@ember/routing';

<template>
  <ul>
    {{#each @model as |post|}}
      <li>
        <LinkTo @route="posts.post" @model={{post.id}}>{{post.title}}</LinkTo>
      </li>
    {{/each}}
  </ul>
</template>

Two behaviors are worth knowing:

  • Passing the id (post.id) means the destination route's model(params) hook runs and loads the data.
  • Passing the whole object (@model={{post}}) means Ember already has the model, so the destination model() hook is skipped. This makes navigation feel instant, but make sure the object has everything the page needs.

For nested dynamic routes, pass several models in order from outer to inner: @models={{array @user.id @post.id}} (the array helper comes from @ember/helper).

Query parameters

JavaScript
<template>
  <LinkTo @route="posts" @query={{hash page=2 sort="newest"}}>Page 2</LinkTo>
</template>

hash builds the object (from @ember/helper). You will see query parameters in detail in the next lesson.

JS How a link gets its href

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The router service

In JavaScript, inject the router service. It is the modern replacement for the older this.transitionTo on routes and controllers.

JavaScript
// app/components/post-form.gjs
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { on } from '@ember/modifier';

export default class PostForm extends Component {
  @service router;
  @service store;

  save = async (event) => {
    event.preventDefault();
    const post = this.store.createRecord('post', { title: 'Hello' });
    await post.save();
    this.router.transitionTo('posts.post', post.id);
  };

  <template>
    <form {{on "submit" this.save}}>
      <button type="submit">Save</button>
    </form>
  </template>
}

The most useful members of the router service:

Member What it does
transitionTo(name, ...models, { queryParams }) Go to a route; adds a history entry.
replaceWith(name, ...models) Go to a route but replace the current history entry.
urlFor(name, ...models) Returns the URL string for a route.
isActive(name, ...models) True if that route is currently active (or a parent of the active one).
currentRouteName Name of the current route, e.g. posts.post.
currentURL The full current URL including query parameters.
refresh() Re-run the models of the current route.

The service also has events (routeDidChange, routeWillChange) that you can use for analytics:

JavaScript
this.router.on('routeDidChange', (transition) => {
  analytics.track(this.router.currentURL);
});

Transitions are promises-like

transitionTo returns a transition object. You can then it, abort() it, or keep it to retry later. A common pattern is remembering a blocked transition and retrying it after login:

JavaScript
// in a route that is blocked
this.session.attemptedTransition = transition;
// later, after login:
this.session.attemptedTransition?.retry();

To navigate when a button is clicked, call the service from an action. For something that is genuinely navigation (the user may want to open it in a new tab), a LinkTo is better than a button, because links are accessible and work with middle-click. Use transitionTo for results of work (after saving, after logging in), not for plain navigation.

JS A navigation history, like the router service

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Programmatic redirects and isActive in templates

The router service can also be used in templates, for example to highlight a menu that covers several routes:

JavaScript
import { service } from '@ember/service';
import Component from '@glimmer/component';
import { LinkTo } from '@ember/routing';

export default class Nav extends Component {
  @service router;

  get inAdmin() {
    return this.router.isActive('admin');
  }

  <template>
    <LinkTo @route="admin" class={{if this.inAdmin "current"}}>Admin</LinkTo>
  </template>
}

Common mistakes

  • A plain anchor for internal links. <a href="/posts"> reloads the whole page and loses app state.
  • Passing an id where a route name is expected. transitionTo('posts.post', 42): the name first, then values for dynamic segments in order.
  • A missing model for a dynamic route. A LinkTo without @model for posts.post throws an error at render time.
  • Calling transitionTo from model(). Use beforeModel, so work is not wasted.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the active class on a LinkTo mean?

    LinkTo marks itself active when its route is part of the current active chain, so a Posts link stays active on a single post page.
  2. 2. What happens when you pass a whole object as @model to a LinkTo for a dynamic route?

    Ember assumes it already has the model. Pass the id when you want the model hook to run.
  3. 3. How do you navigate to the posts.post route for id 7 from a component?

    Inject the router service and use transitionTo with the route name and the segment values.
  4. 4. Which method avoids leaving the redirecting page in the Back history?

    replaceWith swaps the current history entry rather than adding one.

Summary

  • Link with <LinkTo @route="name" @model={{id}}>; it renders a real anchor, adds active and avoids page reloads.
  • Pass an id to run the destination model() hook or a full object to skip it; use @query for query parameters.
  • In code, inject @service router and use transitionTo, replaceWith, urlFor, isActive and currentRouteName.
  • Links are for navigation; transitionTo is for the result of work.

Next: Query Parameters and Loading States