Angular 2 RouteConfig with ES5 and ES6

By Dave Ceddia Comment

RouteConfig in ES5 and ES6

Trying to set up routes in Angular 2, but not using TypeScript? The documentation isn’t too clear on this right now.

In fact, as of this writing, RouteConfig only has docs for TypeScript. There’s nothing for plain old ES5 or ES6 JavaScript.

The official Angular 2 Cheat Sheet for JavaScript says to do this:

var MyComponent = ng.router.RouteConfig([
  { path: '/:myParam', component: MyComponent, name: 'MyCmp' },
  { path: '/staticPath', component: ..., name: ...},
  { path: '/*wildCardParam', component: ..., name: ...}
  constructor: function() {}

But what if you want a Component decorator too? Try sticking a .Component in there and it produces an error:

// none of these work:
var Thing = ng.router.RouteConfig(...).Component(...).Class(...)
var Thing = ng.router.RouteConfig(...).Class(...).Component(...)
var Thing = ng.core.Component(...).Class(...).RouteConfig(...)

What’s the trick?

Decorators return functions that wrap Components

Call RouteConfig with your configuration – this returns a function that, when called with a Component, applies that RouteConfig to that Component. Like this:

HelloApp = ng.router.RouteConfig({})(HelloApp);

The other decorators work the same way. In TypeScript you’d use @Whatever – in ES5 or ES6, call that function as ng.module.Whatever(), then pass your component to the function it returns.

var HelloApp = ng.core.Class(...);
HelloApp = ng.core.Component(...)(HelloApp);
HelloApp = ng.router.RouteConfig(...)(HelloApp);
HelloApp = ng.core.Directive(...)(HelloApp);
// and so on
comments powered by Disqus