Angular 2 - Router

Oct 19, 2015 9:00:00 AM / by daniel.comas

angular 2

 

Hoy vamos a hacer un sencillo ejemplo de como utilizar el routing que incluye Angular 2.

 

HTML

 

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<title>Angular 2</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
</head>
<body>

<h1>Angular 2</h1>
<p>Testing Angular 2 with TypeScript</p>
<my-app></my-app>

</body>
</html>
<script src="https://github.jspm.io/jmcriffey/bower-traceur-runtime@0.0.90/traceur-runtime.js"></script>
<script src="https://jspm.io/system@0.16.js"></script>
<script src="https://code.angularjs.org/2.0.0-alpha.35/angular2.dev.js"></script>
<script src="https://code.angularjs.org/2.0.0-alpha.35/router.dev.js"></script><!--add the router library-->
<script>System.import('app');</script>

 

Component

 

/// <reference path="typings/angular2/angular2.d.ts" />
import {Component, View, bootstrap} from 'angular2/angular2';
import { RouterLink, RouterOutlet, Router, routerInjectables, Location, RouteConfig, LocationStrategy, HashLocationStrategy } from 'angular2/router';
import {Inject, bind} from 'angular2/di';
import {Home} from 'components/home';
import {Home1} from 'components/home1';

@Component({
selector: 'my-app',
viewBindings: [routerInjectables, bind(LocationStrategy).toClass(HashLocationStrategy)] //We can use the strategy that we want HTML5 or Hash
})
//App's menu
@View({
template: `
<nav>
<ul>
<li><a [router-link]=["/home"]>Home</a></li>
<li><a [router-link]=["/home1"]>Home1</a></li>
</ul>
</nav>
<main>
<router-outlet></router-outlet>
</main>
`,
directives: [RouterOutlet, RouterLink]
})
@RouteConfig([
{ path: '/', redirectTo: '/home' },
{ path: '/home', as: 'home', component: Home }, //We will forward the user to the Home component
{ path: '/home1', as: 'home1', component: Home1 } //We will forward the user to the Home1 component
])
class MyAppComponent {
router: Router;
location: Location;
constructor(@Inject(Router) router, @Inject(Location) location) {
this.router = router;
this.location = location;

//We will add a console.log message every time we change the page via URL or href
this.router.subscribe(location => console.log("location changed: " + location));
}
}

//initialize the app
bootstrap(MyAppComponent);

 

Comentar que con el decorator @RouteConfig configuramos el enrutamiento fácilmente y organizadamente.

 

Topics: AngularJS, Component, Ingens Developments, JavaScript, Programación, router, TypeScript

daniel.comas

Written by daniel.comas

Lists by Topic

see all
Servicios gestionados

Categorías

Ver todas