5

So I have been battling to get the router working in Angular2 without using Typescript. I can't seem to find any examples, other than some typescript compiled javascript that uses a decorator function. Is it possible to use Angular 2 Router with plain Javascript?

3 Answers 3

4

You can use router.config() method to specify list of routes. Here is an example written purely in ES5 (see this plunk):

var App = Component({
  selector: 'my-app',
  directives: [RouterOutlet, RouterLink],
  template: (
    '<h2>Hello, World!!!</h2>' +
    '<ul>' +
      '<li><a [router-link]="[\'./Index\']">Index Page</a></li>' +
      '<li><a [router-link]="[\'./Home\']">Home Page</a></li>' +
    '</ul>' +
    '<router-outlet></router-outlet>'
  )
})
.Class({
  constructor: function(router) {
    router.config([
      { path: '/index': component: Index, name: 'Index' },
      { path: '/home':  component: Home,  name: 'Home'  }
    ])
  }
});

App.parameters = [Router];

PS Decorators are part of ES2016 (formerly ES7). They're javascript and supported by Babel. I think you should not be afraid to use them.

Sign up to request clarification or add additional context in comments.

1 Comment

Erm.. that plunk is in typescript?
4

Another example inspired of the Angular2 "Tour of Heroes" tutorial (you can find the full tutorial in plain javascript here: https://programming.sereale.fr/2016/03/22/rails-and-angular2-react-the-tour-of-heroes/):

//= require directives/dashboard-component
//= require directives/heroes-component
//= require directives/hero-detail-component
//= require services/heroes-service

var MyApp = ng.core.Component({
    selector: 'my-app',
    directives: [ng.router.ROUTER_DIRECTIVES],
    providers: [ng.router.ROUTER_PROVIDERS, ng.http.HTTP_PROVIDERS, HeroService], // ng.http.HTTP_PROVIDERS enables to use http and get the list from the server
    template: "<h1>{{title}}</h1> \
                <nav> \
                  <a [routerLink]=\"['Heroes']\">Heroes</a> \
                  <a [routerLink]=\"['Dashboard']\">Dashboard</a> \
                </nav> \
                <router-outlet></router-outlet>"
}).Class({
    constructor: [ ng.router.Router, function(router) {
            router.config([
                { path: '/dashboard', name: 'Dashboard', component: DashboardComponent, useAsDefault: true },
                { path: '/heroes-list', name: 'Heroes', component: HeroesComponent },                
                { path: '/detail/:id', name: 'HeroDetail', component: HeroDetailComponent }
            ]);

            this.title = 'Tour of Heroes';
    }]
});

1 Comment

I get this error: Cannot read property 'ROUTER_DIRECTIVES' of undefined. How do you require/import the modules for ng.router in pure javascript? (without using require() / import statements?)
2

I too was looking for resources regarding Angular 2 deployment in plain JavaScript. I found this article and it was everything I needed to get up and running. Not sure who the author is, but it's very well written and clear.

The other examples show the use of typescript, which was not allowed in our Enterprise environment. (IDK why, I find it really useful.) Fortunately, there is a way to do it with just Javascript (the blog author's plunk illustrates this example.):

  1. During the bootstrap of your project, include the routes dependencies of Angular's ng.router.

    /*global app*/
    'use strict';
    
    (function (ng, app) {
      document.addEventListener('DOMContentLoaded', function () {
        ng.platform.browser.bootstrap(app.Main , [
          ng.router.ROUTER_BINDINGS,
          ng.core.bind(ng.router.LocationStrategy).toClass(ng.router.HashLocationStrategy)
        ]);
     });
    })(this.ng, this.app);
    

    ng: The Angular 2 Library
    app.Main: The main component of the application
    ng.router.ROUTER_BINDINGS: includes all the dependencies to use the router.
    ng.core.bind(...): this line is very important if you don't want to handle page reload logic on the server side. (Without it or configuring of your hosting server, the browser will request a page that only exists client side due to the single page application routing.)

  2. Configure the router to expose the routes to your application and which components that will handle each of them.

    (function (ng, app) {
    
    ng.router.RouteConfig([
        { path: '/home', component: app.HomeComponent, as: 'Home', useAsDefault: true},
        { path: '/test', component: app.TestComponent, as: 'Test'}
    ])(app.Main);
    
    })(window.ng, window.app);
    

    app.HomeComponent: configured as an example component that will be our default route.
    app.TestComponent: configured as another example component.

  3. Update the links on the main page that will handle the routing:

    <ul>
      <li>
        <a [routerLink]="['Home']">Home</a>
      </li>
      <li>
        <a [routerLink]="['Test']">Test</a>
      </li>
    </ul>
    <router-outlet></router-outlet>
    

    routerLink: binds a target route by it's name to a link tag.
    router-outlet: placeholder for the router to include the different views of components as the user navigates the application.

  4. Ensure you include the ng.router.ROUTER_DIRECTIVES into the directives of your Main component so that Angular can identify the directives in the templates.

  5. Create the components use for the routing:

    //home.component.js
    app.register ('HomeComponent', function (ng) {
      return ng.core.
    
      Component({
        template: '
    <div>Hello {{name}}!</div>
    ',
      }).
      Class({
        constructor:function () {
          this.name ='world';
        }
      });
    
    });
    
    //test.component.js
    app.register ('TestComponent', function (ng) {
      return ng.core.
    
      Component({
        template: 'This is a testing page'
      }).
      Class({
        constructor: function () {}
      });
    
    });
    
  6. Your single page application should now be able to handle both the routing and page reloads using only JavaScript.

Thanks again to the author of this blog and the time he spent creating this plunk

2 Comments

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
The other answers either use TypeScript or don't handle the page reloads. (Without the HashLocation and/or server configuration, the routing will break on page reloads.) I'm still new to posting answers, please let me know if the above is better suited for the community.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.