Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Routing in plain Javascript (No Typescript)

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?

like image 712
nickgzzjr Avatar asked Nov 14 '15 17:11

nickgzzjr


People also ask

Can I use Angular without TypeScript?

Angular2 is available in TypeScript, JavaScript and Dart. No need to use TypeScript.

Can we use JavaScript instead of TypeScript in Angular?

Yes, you can.

Is angular 2 JavaScript or TypeScript?

AngularJS is by far the most popular JavaScript framework available today for creating web applications. And now Angular 2 and TypeScript are bringing true object oriented web development to the mainstream, in a syntax that is strikingly close to Java 8.

Does angular 2 use TypeScript?

Angular 2 is built on TypeScript, which uses ES6 syntax and compiles to vanilla JavaScript. Standard ES5 JavaScript is also valid TypeScript, so you can still use your existing code.


3 Answers

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.

like image 118
alexpods Avatar answered Nov 14 '22 21:11

alexpods


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';
    }]
});
like image 44
Johnf39 Avatar answered Nov 14 '22 22:11

Johnf39


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

like image 43
Bryan Cote-Chang Avatar answered Nov 14 '22 21:11

Bryan Cote-Chang