Download presentation
Presentation is loading. Please wait.
Published byHillary Hensley Modified over 5 years ago
1
CS5220 Advanced Topics in Web Programming Angular – Routing
Chengyu Sun California State University, Los Angeles
2
The Need for Routing Usually we have different pages in a web application How do we have different "pages" in a SPA? Home About Login
3
Angular Routing Load different components based on different URL About
Login Component Home About Login HomeComponent AppComponent
4
Add A Routing Module The routing option of ng new
Add an AppRoutingModule Import the routing module in AppModule Add a <router-outlet> in App component template, which is a placeholder for the components to be loaded.
5
AppRoutingModule import { NgModule } from '@angular/core';
import { Routes, RouterModule } from const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
6
RouterModule RouterModule.forRoot(routes) returns a RouterModule that is configured with routes AppRoutingModule imports this module, then exports it so the rest of the application can use it You can specify routing directly in AppModule, but using an AppRoutingModule is recommended (for centralizing route management in large applications)
7
The forRoot() Convention
forRoot() returns a module that should be imported by the root module (i.e. the module used for bootstrapping the application) Use forChild() if you want to add routing to a feature module
8
Routes Routes specify the mappings between paths and components, e.g.
const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'login', component: LoginComponent } ];
9
Basic Routing const routes: Routes = [
{ path: 'block1', component: Block1Component }, { path: 'block2', component: Block2Component } ]; In template: <a routerLink="block1">Block 1</a> <a routerLink="block2">Block 2</a>
10
Why routerLink instead of href?
See the difference using Chrome's Developer Tools (Network tab) Clicking on a routerLink does NOT send a request – the address URL is changed through HTML5 history API
11
routeLink as @Input <a routerLink="block1">Block 1</a>
Link is hard-coded in template <a routerLink="block1">Block 1</a> Allow setting link with dynamic data from code <a [routerLink]="'block1'">Block 1</a> <a [routerLink]="['block1']">Block 1</a>
12
Route Segments <a routerLink="user/bob">Bob</a>
<a [routerLink]="['user', name]">{{name}}</a>
13
Wildcard Route const routes: Routes = [ { path: 'about', component: AboutComponent }, { path: 'login', component: LoginComponent }, { path: '**', component: PageNotFoundComp} ]; Catch un-matched routes and display a PageNotFound component Route order matters so make sure the wildcard route is listed last
14
Navigate to Route in Code
Example: click a button in Block1 to go to Block2 class Block1Component { constructor(private router: Router) {} goToBlock2(): boolean { this.router.navigate( ['block2'] ); }
15
Attach Information To Route
Path parameters, e.g. /user/:id Matrix parameters, e.g. /user;fn=John;ln=Doe Query parameters, e.g. /user?id= Path fragment, e.g. /user#profile
16
Specify Route Parameters
const routes: Routes = [ { path: 'block1/:id', component: Block1Component } ]; In template: <a routerLink="block1/1">Block 1</a> <a [routerLink]="['block1', 1]">Block 1</a> In component class: this.router.navigate(['block1', 1]);
17
Specify Matrix Parameters
<a [routerLink]="['block1',{x:10, y:20}]''> this.router.navigate([ 'block1', {x:10, y:20} ]);
18
Specify Query Parameters
<a routerLink="block2'' [queryParams]="{id: 1}"> this.router.navigate( ['block2'], { queryParams: { id: 1 } } );
19
Specify Path Fragment <a routerLink="block2'' fragment="anchor">
this.router.navigate( ['block2'], { fragment: 'anchor' } );
20
Retrieve Information from Route
Inject an ActivatedRoute in component constructor Subscribe to params (for both route and matrix parameters) or queryParams or fragment in ngOnInit() Unsubscribe in ngOnDestroy()
21
Example: Getting Parameters
constructor( private router: Router, private route: ActivatedRoute ) {} ngOnInit() { this.paramsSub = this.route.params.subscribe( params => { this.id = params['id'] || 0; this.x = params['x']; this.y = params['y']; }); }
22
Why "Subscribing" to Parameters?
Add console.log() in ngOnInit() and ngOnDestroy() to see when a component is initialized/destroyed Angular reuses components to improve performance, so the same component instance needs to handle changing parameters
23
Redirect pathMatch can be either 'prefix' (default) or 'full'
const routes: Routes = [ { path: 'block1', component: Block1Component }, { path: 'blockx', redirectTo: 'block1', pathMatch: 'full'} ]; pathMatch can be either 'prefix' (default) or 'full'
24
Children Routes { path: 'block3', component: Block3Component, children: [ { path: 'block4', component: Block4Component }, { path: 'block5', component: Block5Component } ] } Children components would appear in the <router-outlet> in the parent
25
Named Router Outlet Template:
<router-outlet><router-outlet> <router-outlet name="other"></router-outlet> Routes: { path: 'block6', component: Block6Component, outlet: 'other' }
26
Route Guard Determine whether a user can navigate to or away from a route Types of route guard CanActivate: navigate to a route CanActivateChild: navigate to a child route CanDeactivate: navigate away from a route CanLoad: used for lazy-loaded modules
27
CanDeactivate CanDeactivate guard is usually used to remind the user of something before the user navigates away from a component As such, it requires a component that displays a confirmation dialog
28
Add A Route Guard Use Angular CLI to generate a guard
Add it to the route that needs to be protected, e.g. { path: 'block7', component: Block7Component, canActivate: [CanActivateGuard] } More examples in TechIT 2 Client
29
Readings Angular Router by Victor Savkin
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.