Introduction to Ember.js Routable components

Introduction to Ember.js Routable components

Routable Components is used to replace Controller in the component-centric model for Ember.js 2.0, more details can refer to this RFC.

Edit (6/8/2015): Add method which use route to render routable components.

This is a rough introduction to Routable components as #11939 had merged to canary. The syntax is subject to change. There are two way to use routable component, without route or with route.

Setup:

1. Use Ember.js canary build
Edit bower.json then run bower install (details)

"dependencies": {
  "ember": "components/ember#canary"
}

2. Enable experimental features
Edit config/environment.js.

var ENV = {
  EmberENV: {
    FEATURES: {
      'ember-routing-routable-components': true
    }
  },
};

3. Add new component:

ember g component home-route

As ember-cli not yet support component without hyphen. You need to create component named home-route for example.

Method 1: Component without route/model

1. Declare routable component
Edit app/components/home-route.js

export default Ember.Component.extend({
  isGlimmerComponent: true,
  name: 'Home'
});

isGlimmerComponent flag is used to avoid naming collisions with existing components and name is for logging.

2. Add content

Edit app/templates/components/home-route.hbs

<p>This is {{name}} route.</p>

3. Edit app/router.js

Router.map(function() {
  this.route('home-route', { path: '/' });
});

Route name is the same as component's name.

Method 2: Render component in route's renderTemplate

1. Add route

ember g route home

2. Render component in route

Bug should be fixed in #12154.

Edit app/routes/home.js & Remove home template (templates/home.hbs)

App.HomeRoute = Ember.Route.extend({
  renderTemplate() {
    this.render({ component: 'home-route' });
  }
});

You can also pass model to component in model:

App.HomeRoute = Ember.Route.extend({
  model() {
    return {
      name: 'Home'
    };
  }
});

3. Add content

Edit app/templates/components/home-route.hbs

<p>This is {{attrs.model.name}} route.</p> 

Result:
Result