Angularjs Routing — Angular1 vs Angular2

Supun Dharmarathne
technodyne
Published in
2 min readAug 22, 2016

Before we start and to make sure we are in line on the terminology, I will use the name AngularJS to define AngularJS 1.x and Angular2 to define AngularJS 2.x.

AngularJS

To enable Hash (#) urls, set the following configuration. This will shift within two nodes.(HTML5 enable mode or not)

[sourcecode language=”javascript”]
$locationProvider.html5Mode(true);
[/sourcecode]

Angular2

In Angular2 , same modes are called as PathLocationStrategy and HashLocationStrategy

PathLocationStrategy is the default strategy which is used by Angular2. This is equivalent to HTML5 mode in AngularJS.

[sourcecode language=”javascript”]
import {ROUTER_PROVIDERS, APP_BASE_HREF} from ‘angular2/router’;

bootstrap(yourApp, [
ROUTER_PROVIDERS, // includes binding to PathLocationStrategy
provide(APP_BASE_HREF, {useValue: ‘/my/prefix/here’})
]);
[/sourcecode]

HashLocationStrategy will add hash fragment to URL.

[sourcecode language=”javascript”]
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from ‘angular2/router’; // works only for rc6 ,
// for others import { ROUTER_PROVIDERS } from ‘@angular/router-deprecated’;
// import {LocationStrategy,HashLocationStrategy }from ‘@angular/common’;
bootstrap(yourApp, [
ROUTER_PROVIDERS,
provide(LocationStrategy, {useClass: HashLocationStrategy})
]);
[/sourcecode]

Define Routes

AngularJS

[sourcecode language=”javascript”]
$stateProvider.state(‘home’, {
url: ‘/’,
templateUrl: ‘home.html’,
controller: ‘HomeCtrl’
}).state(‘about’, {
url: ‘/about’,
templateUrl: ‘about.html’,
controller: ‘AboutCtrl’
})
[/sourcecode]

Angular2

[sourcecode language=”javascript”]
import {RouteConfig, Route} from ‘angular2/router’;
import {MyComponentHome, MyComponentAbout} from ‘./myComponents’;
@Component({
selector: “app”
})
@RouteConfig([
new Route({ path: ‘/’, component: MyComponentHome, name: ‘Home’ }),
new Route({ path: ‘/about’, component: MyComponentAbout, name: ‘About’ })
])
export class App {…}
[/sourcecode]

Template Update

AngularJS

[sourcecode language=”html”]
<body>
<ui-view>
<i>Some content will load here!</i>
</ui-view>
</body>
[/sourcecode]

Angular2

[sourcecode language=”javascript”]
import {RouterOutlet} from ‘angular2/router’;
@Component({
selector: “app”
})
@View({
directives: [RouterOutlet]
template: `
<router-outlet></router-outlet>
`
})
[/sourcecode]

Navigate through views

AngularJS

[sourcecode language=”html”]
<a ui-sref=”home”>Home page</a>
<a ui-sref=”about”>About page</a>
[/sourcecode]

Angular2

[sourcecode language=”javascript”]
import {RouterLink} from ‘angular2/router’;
@Component({
selector: “menu”,
directives: [RouterLink],
template: `
<a [routerLink]=”[‘./Home’]”>Home page</a>
<a [routerLink]=”[‘./About’]”>About page</a>
`
})
export class Menu {…}
[/sourcecode]

--

--