Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Angular 2 RouteConfig with ES5 and ES6

0.00/5 (No votes)
15 Feb 2016CPOL 8K  
Angular 2 RouteConfig with ES5 and ES6

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:

JavaScript
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:

JavaScript
// 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:

JavaScript
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.

JavaScript
var HelloApp = ng.core.Class(...);
HelloApp = ng.core.Component(...)(HelloApp);
HelloApp = ng.router.RouteConfig(...)(HelloApp);
HelloApp = ng.core.Directive(...)(HelloApp);
// and so on

Angular 2 RouteConfig with ES5 and ES6 was originally published by Dave Ceddia at Angularity on February 15, 2016.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)