Angular2 router
Features
- Component based navigation
- Nested views
- Sample use case: tabs
- CanActivate - Can navigate to component?
- Sample use case: restricted account page
- CanDeactivate - Can get out of component?
- Confirm changing route in edit page
ng g route
In current version of ng-cli, the generation of route is not possible. but ng g comopnent will be enough
- Create 'routes' folder under src/app
- Navigate to that folder
- Create route components:
ng g component home-route
ng g component event-route
ng g component login-route - Move app.component logic, imports to home-route component
Config routes
New file for defining the routes- app.routes.ts
Locate it in src/app root folder
import { provideRouter, RouterConfig } from '@angular/router';
import { HomeRouteComponent } from './routes/home-route';
...
const routes: RouterConfig = [
{ path: '', component: HomeRouteComponent },
{ path: 'events/:slug', component: EventRouteComponent }
...
];
export const appRouterProviders = [
provideRouter(routes)
];
Config routes
Add it to app bootstrap under main.ts
So the app will recognise the routes configured
bootstrap(AppComponent, [
...
appRouterProviders,
...
]);
Router outlet
placeholder element that will show the route component inside.
open app.component.html
<app-navbar></app-navbar>
<router-outlet></router-outlet>
Linking to route
- Import ROUTER_DIRECTIVES and use it app-wide:
- Add to bootstrap in main.ts
- import ROUTER_DIRECTIVES:
- Add to bootstrap in main.ts
<a [routerLink]="['/events/' + event.slug]">{{event.title}}</a>
Using in template:
bootstrap(AppComponent, [
...
provide(PLATFORM_DIRECTIVES,
{
useValue: [ROUTER_DIRECTIVES],
multi: true
})
...
]);
import { ROUTER_DIRECTIVES } from '@angular/router';
Get route param
- Import ActivatedRoute in the desired route component
- Use in constructor:
- Get the param:
import { ActivatedRoute } from '@angular/router';
ngOnInit() {
this.route.params
.map(params => params['id'])
.subscribe((id) => {
console.log(id)
});
}
constructor(private route: ActivatedRoute)
Angular2 Router
By Dvir Hazout
Angular2 Router
- 632