angular 2.0 routing and navigation
TRANSCRIPT
Angular 2.0 Routing & Navigation
Eyal Vardi
Site: http://ng-course.org
Blog: eyalVardi.wordpress.com
Agenda Installation & Setup RouteConfig Decorator RouterOutlet & RouterLink Directives Link Parameters Array RouteParams & RouteData Services Router Lifecycle Hooks
Index.html Setup Add the angular router script.
<script src="router.dev.js"></script>
import { RouteConfig, ROUTER_PROVIDERS, ROUTER_DIRECTIVES , HashLocationStrategy, LocationStrategy} from 'angular2/router';
Installationimport {bootstrap} from 'angular2/platform/browser';import { ROUTER_PROVIDERS, ROUTER_DIRECTIVES from 'angular2/router';
bootstrap(AppComponent, [ ROUTER_PROVIDERS]);
@Component({ selector: 'my-app', template: '<h1>My First Angular 2 App</h1>', directives: [ROUTER_DIRECTIVES]})export class AppComponent { }
Routing Strategies HashLocationStrategy ('#/') PathLocationStrategy (HTML 5 Mode)import {bootstrap} from 'angular2/platform/browser';import { ROUTER_PROVIDERS,ROUTER_DIRECTIVES, HashLocationStrategy, LocationStrategy} from 'angular2/router';
bootstrap(AppComponent, [ ROUTER_PROVIDERS, provide(LocationStrategy, {useClass:HashLocationStrategy})]);
Path Location Strategy (HTML 5 Mode) Must set base URL. How to set the base URL, 3 options:
bootstrap( App, [ ROUTER_PROVIDERS, provide( APP_BASE_HREF , { useValue: '/' }) ]);
<script> document.write( '<base href="' + document.location + '" />');</script>
<base href="/" >1.
2.
3.
RouterLink & RouterOutlet
<router-outlet>
<a [routerLink]="['Go']">Go</a>
Code : router.navigate( ['Go'] );
HTML : <a [routerLink]="['Go']">Go</a>
Component:
Template
Route Definition path - the URL path segment for this
route. name - the name of the route. component - the Component associated with
this route. useAsDefault - makes this route the default
route. redirectTo@Component({ ... })@RouteConfig([ {path:'/home‘ , name: 'Home' , component: Home}, {path:'/products' , name: 'Products', component: Products}, {path:'/users' , name: 'Users' , component: Users} ]) export class AppComponent { }
Url : http://ev.com/
<router-outlet>
Component App
Home | Products | Users |
<a [routerLink]="[ '
Url : http://ev.com/
<router-outlet>
Component App
Home | Products | Users |
Products
<router-outlet>
Product 1
Product 2
Product 3
Product 4
Product 5
Product 6
Product 7
Product 8
products/
<a [routerLink]="[ '
products ',
Url : http://ev.com/
<router-outlet>
Component App
Home | Products | Users |
Products
<router-outlet>
Product 1
Product 2
Product 3
Product 4
Product 5
Product 6
Product 7
Product 8
products/product/1
<router-outlet>
Details | Price | Spec |
<a [routerLink]="[ '
products ','product',{id:1}]">
Route Definition@Component({ ... })@RouteConfig([ {path:'/home' , name: 'Home' , component: HomeComp}, {path:'/products/...' , name: 'Products', component: ProductsComp}, {path:'/Users' , name: 'Users' , component: UsersComp} ])export class AppComponent { }
@Component({ ... })@RouteConfig([ {path:'/product/:id/...',name: 'Product', component: ProductComp}])export class ProductsComponent { }
@Component({ ... })@RouteConfig([ {path:'/Details', name: 'Details',component: DetailsComp}, {path:'/Price' , name: 'Price' ,component: PriceComp}, {path:'/Spec' , name: 'Spec' ,component: SpecComp} ])export class ProductComponent { }
App
Products
Product
Link Parameters Array
['Products']
[routerLink]
['Products','Product']
[routerLink]
['./Product']
[routerLink]
[routerLink]
['/Products','Product']
Query Parameters We use route parameters to specify a
parameterized value within the route URL. URL query Route parameters object{path:'/:id', name:'Product', component:Product}
<a [routerLink]="['Product', {id:1}]">Product 1</a>
router.navigate(['Product' ,'{id:8}']);
RouteParams
@Component({ template: 'user: {{id}}' }) class UserCmp { id: string; constructor(params: RouteParams) { this.id = params.get('id'); } }
RouteData@Component({...})@View({directives: [ROUTER_DIRECTIVES]})@RouteConfig([{ path: '/user/:id' , component: UserCmp , as: 'UserCmp' , data: {isAdmin: true}}])class AppCmp {}
@Component({ template: 'user: {{isAdmin}}' })class UserCmp { string: isAdmin; constructor(data: RouteData) { this.isAdmin = data.get('isAdmin'); } }
Instructionimport {Component} from 'angular2/core';import {Router,ROUTER_DIRECTIVES,RouteConfig} from 'angular2/router';
@Component({directives: [ROUTER_DIRECTIVES]})@RouteConfig([{...}])class AppCmp { constructor(router: Router) {
var instruction = router.generate(['/MyRoute']); router.navigateByInstruction(instruction);
}}
Matrix URL Notation Matrix URL notation is an idea first floated in a 1996
proposal by the founder of the web, Tim Berners-Lee.
Although matrix notation never made it into the HTML standard, it is legal and it became popular among browser routing systems as a way to isolate parameters belonging to parent and child routes.
<a [routerLink]="['Product', {id:1,foo:3}]">Product 1</a>
localhost:3000/product/;id=1;foo=foo
Router Lifecycle Hooks
Router Lifecycle Hooks
canDeactivate
OnDeactivate
OnActivate
['Products'][routerLink]
CanActivate
@CanActivate Decorator The @CanActivate function is called
before the component is instantiated, Must be an annotation.@CanActivate((next, prev) => boolean | Promise<boolean>)
Sample:
@Component({selector: 'control-panel-cmp‘, template: `<div>Settings: ...</div>`
})@CanActivate(checkIfWeHavePermission)class ControlPanelCmp {}
CanReuse & OnReuse Determine whether a component should
be reused across routes, or whether to destroy and instantiate a new component. Use URL Param’s to load right object.
canReuse
OnReuse
[routerLink]
View I
Cancelling Route Changes
View IICancel
OK
routerCanDeactivate( next: ComponentInstruction, prev: ComponentInstruction) : any { return new Promise<boolean>((resolve, reject) => resolve(window.confirm('Continue?')));}
Lazy Loading (AsyncRoute class) AsyncRoute is a type of RouteDefinition
used to route a path to an asynchronously loaded component.
@RouteConfig([ new AsyncRoute({ path: '/home', loader: () => System.import('./Home').then(m=>m['Home']), name: 'Home' }), {path:'/users/...', name: 'Users', component: Users}])export class App { }
Thankseyalvardi.wordpress.com
Eyal Vardi
Site: http://ng-course.org
Blog: eyalVardi.wordpress.com