Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / Javascript

Angular 2 RouteConfig with ES5 and ES6

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
15 Feb 2016CPOL 7.8K   2  
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.

This article was originally posted at https://daveceddia.com/feed.xml

License

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


Written By
United States United States
Dave is a Software Engineer in the Boston area and writes about AngularJS and other JavaScript things over at daveceddia.com

Comments and Discussions

 
-- There are no messages in this forum --