
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: ...}
]).Class({
constructor: function() {}
});
But what if you want a Component decorator too? Try sticking a .Component in there and it produces an error:
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);
Angular 2 RouteConfig with ES5 and ES6 was originally published by Dave Ceddia at Angularity on February 15, 2016.
CodeProject