SlideShare a Scribd company logo
1 of 49
Download to read offline
8 things you didn't know
about the Angular Router,
you won't believe #6!
Laurent Duveau – May 21th 2019
Who am I ?
Laurent Duveau
• I live in Montreal, Canada
• Founder of the Angular Academy
• 2-day Angular Classroom Training
• 152 classes in the last 3 years!
• @LaurentDuveau
Who am I ?
Laurent Duveau
• I live in Montreal, Canada
• Founder of the Angular Academy
• 2-day Angular Classroom Training
• 152 classes in the last 3 years!
• @LaurentDuveau
I LOVE
ANGULAR!
Angular Router
Client-Side Routing
Navigate between views in a SPA just like you
navigate pages in a normal site
Refresh the page and keep the location in app
Bookmark the URL, share it with others
Works with Browsers back/forward history
Sample
project Products Module
App Module
Sample
project Products Module
App Module
const routes: Routes = [
{path: '', redirectTo:'/home', pathMatch:'full'},
{path: 'home', component: HomeComponent},
{path: 'contact', component: ContactComponent},
];
const routes: Routes = [
{
path: 'products',
component: ProductsComponent,
children: [
{ path: '', component: ProductListComponent },
{ path: 'insert', component: ProductInsertComponent },
{ path: ':id', component: ProductDetailComponent }
]
}
];
DEMONSTRATION
7
#1
Lazy Loading
8
Lazy Loading ?
Loading a module later
Better startup performance
The delay is during the loading on demand
Happens with the Router!
Lazy load the Products Module!
const routes: Routes = [
{path: '', redirectTo:'/home', pathMatch:'full'},
{path: 'products', loadChildren:'./products/products.module#ProductsModule'},
{path: 'home', component: HomeComponent},
{path: 'contact', component: ContactComponent},
];
app.routing.ts
New syntax coming with Angular V8 and Ivy!
const routes: Routes = [
{path: '', redirectTo:'/home', pathMatch:'full'},
{path: 'products', loadChildren:'./products/products.module#ProductsModule'},
{path: 'products', loadChildren: () =>
import('./products/products.module').then(m => m.ProductsModule)},
{path: 'home', component: HomeComponent},
{path: 'contact', component: ContactComponent},
];
app.routing.ts
Old syntax still here for non-ivy
or Angular 7 and below
Using dynamic import
(new web standard)
the new rendering pipeline
Well… use one syntax or the other, not both together!
Make its routes relative to ‘products/‘
products.routing.ts
products.routing.ts
const routes: Routes = [
{
path: 'products',
component: ProductsComponent,
children: [
{ path: '', component: ProductListComponent },
{ path: 'insert', component: ProductInsertComponent },
{ path: ':id', component: ProductDetailComponent }
]
}
]; const routes: Routes = [
{
path: '',
component: ProductsComponent,
children: [
{ path: '', component: ProductListComponent },
{ path: 'insert', component: ProductInsertComponent },
{ path: ':id', component: ProductDetailComponent }
products.routing.ts … so we do not want
http://mysite.com/products/products
We lazy load this module with:
http://mysite.com/products
Do not import lazy loaded modules!
@NgModule({
imports:[BrowserModule, HttpModule, ProductsModule],
})
export class AppModule { }
app.module.ts
@NgModule({
imports:[BrowserModule, HttpModule],
})
export class AppModule { }
app.module.ts
If you leave it here… you’ll get
the opposite effect (eager load)
DEMONSTRATION
14
#2
Preloading
Modules
15
Preloading Modules!
Preload a lazy-loadable module in the background
while the user is interacting with your application
When module is needed it might be available
immediately
This is about anticipation
16
Preloading Modules!
* Pictures by Victor Savkin – vsavkin.com
Preloading Modules!
* Pictures by Victor Savkin – vsavkin.com
Preloading Modules!
* Pictures by Victor Savkin – vsavkin.com
Preloading Modules!
* Pictures by Victor Savkin – vsavkin.com
Preloading Modules!
One built-in preloading strategy: PreloadAllModules
Create your Custom Preloading Strategy!
Class that implements PreloadingStrategy
@NgModule({
imports: [RouterModule.forRoot(routes,
{ preloadingStrategy: PreloadAllModules })],
exports: [RouterModule],
})
export class AppRoutingModule { }
Preloading Modules
ngx-quicklink (Open source library)
Router preloading strategy which automatically
downloads lazy-loaded modules associated with all
the visible links in the viewport when the browser is
idle.
22
https://www.npmjs.com/package/ngx-quicklink
DEMONSTRATION
23
#3
Router Events
24
Router Events
Event Description
NavigationStart Navigation starts
RoutesRecognized Router parses the URL and the routes are recognized
RouteConfigLoadStart Before the Router lazy loads a route configuration
RouteConfigLoadEnd After a route has been lazy loaded
NavigationEnd Navigation ends successfully
NavigationCancel Navigation is canceled. This is due to a Route Guard
returning false during navigation
NavigationError Navigation fails due to an unexpected error
+ more…
Router Events
26
@Component({
selector: 'my-app',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {}
ngOnInit() {
this.router.events
.subscribe((event) => {
if (event instanceof NavigationEnd) {
console.log('NavigationEnd:', event);
}
});
}
}
#4
Diagnostic with
traces
27
Activate Router traces
@NgModule({
imports: [RouterModule.forRoot(routes,
{ enableTracing: environment.production ? false : true }
)]
})
export class AppRoutingModule { }
app-routing.module.ts
DEMONSTRATION
29
#5
Auxiliary Routes
30
Auxiliary Routes
Navigation happens in a
<router-outlet></router-outlet>
We can have more than one!
So we can navigate to several routes at the same time!
Auxiliary Routes
Create a named router-outlet
Add a route to target this outlet
Link to navigate to the outlet
<router-outlet></router-outlet>
<router-outlet name="side"></router-outlet>
{path:'contact', component:ContactComponent, outlet:'side'}
<a [routerLink]="[{outlets: {side:['contact']}}]">Contact</a>
DEMONSTRATION
33
#6
Routes Transitions
(Animations)
34
Animations
Define animations files
import { trigger, animate, transition, style } from '@angular/animations';
export const fadeInAnimation =
// trigger name for attaching this animation to an element using the
[@triggerName] syntax
trigger('fadeInAnimation', [
// route 'enter' transition
transition(':enter', [
// css styles at start of transition
style({ opacity: 0 }),
// animation and styles at end of transition
animate('.5s', style({ opacity: 1 }))
]),
]);
fade-in.animation.ts
Animations
Import BrowserAnimationsModule
Use in @Component decorator
@Component({
selector: 'app-product-list’,
animations: [fadeInAnimation],
host: { '[@fadeInAnimation]': ''}
})
export class MyComponent {
animation to use
attached to host to run
animation when
component is activated
DEMONSTRATION
37
#7
Guards
38
Routes Guards
CanActivate CanDeactivate
NavigationNavigation
Component
Decides if a route can be activated
- User logged-in ?
Decides if a route can be deactivated
- Form saved ?
Routes Guards
40
export class LoginRouteGuard implements CanActivate {
constructor(
private loginService: LoginService,
private router: Router) {}
canActivate() {
if(!this.loginService.isLoggedIn()) {
this.router.navigateByUrl("/login");
return false;
}
return true;
}
}
login-route-guard.service.ts
{ path: 'admin', component: AdminComponent, canActivate: [LoginRouteGuard] },
app-routing.module.ts
DEMONSTRATION
41
#8
Passing data via state
object during navigation
(new in 7.2)
42
Passing Data between Routes
Setting the State
@Component({
template: `<a (click)="navigateWithState()">Go</a>`,
})
export class AppComponent {
constructor(public router: Router) {}
navigateWithState() {
this.router.navigateByUrl('/123', { state: { hello: 'world' } });
}
}
@Component({
selector: 'my-app',
template: `
<a routerLink="/details" [state]="{ hello: 'world' }">Go</a>`,
})
export class AppComponent {}
Imperative navigation
Declarative navigation
OR
Passing Data between Routes
Reading the State
@Component({
selector: 'app-details-page',
template: '<pre>{{ state$ | async | json }}</pre>'
})
export class DetailsPageComponent implements OnInit {
state$: Observable<object>;
constructor(public activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.state$ = this.activatedRoute.paramMap
.pipe(map(() => window.history.state))
}
}
DEMONSTRATION
45
#9
Route Resolver
46
Bonus!
Route Resolver
Pre-fetching component data before navigating
Avoid a blank component while waiting for the
data to be returned from the server
Pre-fetch data from the server so it's ready the
moment the route is activated!
Create a service and implement the Resolve
interface
DEMONSTRATION
48
8 things you didn't know about the Angular Router, you won't believe #6!

More Related Content

What's hot

What's hot (20)

Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developers
 
Angular 2... so can I use it now??
Angular 2... so can I use it now??Angular 2... so can I use it now??
Angular 2... so can I use it now??
 
Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Building Universal Applications with Angular 2
Building Universal Applications with Angular 2
 
Beyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and moreBeyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and more
 
Docker - An Introduction
Docker - An IntroductionDocker - An Introduction
Docker - An Introduction
 
Angular 2 - Better or worse
Angular 2 - Better or worseAngular 2 - Better or worse
Angular 2 - Better or worse
 
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET Developers
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
An Overview of Angular 4
An Overview of Angular 4 An Overview of Angular 4
An Overview of Angular 4
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?
 
Angular, the New Angular JS
Angular, the New Angular JSAngular, the New Angular JS
Angular, the New Angular JS
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
Angular 1.x vs 2 - In code level
Angular 1.x vs 2 - In code levelAngular 1.x vs 2 - In code level
Angular 1.x vs 2 - In code level
 
Angular 5
Angular 5Angular 5
Angular 5
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture project
 

Similar to 8 things you didn't know about the Angular Router, you won't believe #6!

Angular2RoutingSetupByShubham
Angular2RoutingSetupByShubhamAngular2RoutingSetupByShubham
Angular2RoutingSetupByShubham
Shubham Verma
 
What is your money doing?
What is your money doing?What is your money doing?
What is your money doing?
Alfonso Fernández
 
reactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdfreactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdf
sunilkhetpal
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 

Similar to 8 things you didn't know about the Angular Router, you won't believe #6! (20)

Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Angular routing
Angular routingAngular routing
Angular routing
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Web components with Angular
Web components with AngularWeb components with Angular
Web components with Angular
 
Angular2RoutingSetupByShubham
Angular2RoutingSetupByShubhamAngular2RoutingSetupByShubham
Angular2RoutingSetupByShubham
 
ngNewRouter
ngNewRouterngNewRouter
ngNewRouter
 
What is your money doing?
What is your money doing?What is your money doing?
What is your money doing?
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
Angular2 routing
Angular2 routingAngular2 routing
Angular2 routing
 
Routing in NEXTJS.pdf
Routing in NEXTJS.pdfRouting in NEXTJS.pdf
Routing in NEXTJS.pdf
 
How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
 
reactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdfreactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdf
 
Angular resolver tutorial
Angular resolver tutorialAngular resolver tutorial
Angular resolver tutorial
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applications
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
 
Jan 2017 - a web of applications (angular 2)
Jan 2017 - a web of applications (angular 2)Jan 2017 - a web of applications (angular 2)
Jan 2017 - a web of applications (angular 2)
 
Neoito — Routing and navigation in Angular
Neoito — Routing and navigation in AngularNeoito — Routing and navigation in Angular
Neoito — Routing and navigation in Angular
 
Aurelia Meetup Paris
Aurelia Meetup ParisAurelia Meetup Paris
Aurelia Meetup Paris
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 

More from Laurent Duveau

More from Laurent Duveau (20)

Shit happens… debugging an Angular app.
Shit happens… debugging an Angular app.Shit happens… debugging an Angular app.
Shit happens… debugging an Angular app.
 
De 0 à Angular en 1h30! (french)
De 0 à Angular en 1h30! (french)De 0 à Angular en 1h30! (french)
De 0 à Angular en 1h30! (french)
 
Angular 6, CLI 6, Material 6 (french)
Angular 6, CLI 6, Material 6 (french)Angular 6, CLI 6, Material 6 (french)
Angular 6, CLI 6, Material 6 (french)
 
Debugging an Angular App
Debugging an Angular AppDebugging an Angular App
Debugging an Angular App
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET Developers
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET Developers
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET Developers
 
Introduction to Angular with TypeScript for .NET Developers
Introduction to Angular with TypeScript for .NET DevelopersIntroduction to Angular with TypeScript for .NET Developers
Introduction to Angular with TypeScript for .NET Developers
 
Introduction à Angular 2
Introduction à Angular 2Introduction à Angular 2
Introduction à Angular 2
 
ngconf 2016 (french)
ngconf 2016 (french)ngconf 2016 (french)
ngconf 2016 (french)
 
Microsoft Edge pour les développeurs web
Microsoft Edge pour les développeurs webMicrosoft Edge pour les développeurs web
Microsoft Edge pour les développeurs web
 
Microsoft Edge pour les développeurs web
Microsoft Edge pour les développeurs webMicrosoft Edge pour les développeurs web
Microsoft Edge pour les développeurs web
 
Introduction to SPAs with AngularJS
Introduction to SPAs with AngularJSIntroduction to SPAs with AngularJS
Introduction to SPAs with AngularJS
 
Xamarin.Forms [french]
Xamarin.Forms [french]Xamarin.Forms [french]
Xamarin.Forms [french]
 
Back from Xamarin Evolve 2014
Back from Xamarin Evolve 2014Back from Xamarin Evolve 2014
Back from Xamarin Evolve 2014
 
Windows App Studio
Windows App StudioWindows App Studio
Windows App Studio
 
Windows 8: Live tiles, badges et notifications toasts [french]
Windows 8: Live tiles, badges et notifications toasts [french]Windows 8: Live tiles, badges et notifications toasts [french]
Windows 8: Live tiles, badges et notifications toasts [french]
 
L'opportunité Windows 8 pour les développeurs
L'opportunité Windows 8 pour les développeursL'opportunité Windows 8 pour les développeurs
L'opportunité Windows 8 pour les développeurs
 

Recently uploaded

Recently uploaded (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

8 things you didn't know about the Angular Router, you won't believe #6!

  • 1. 8 things you didn't know about the Angular Router, you won't believe #6! Laurent Duveau – May 21th 2019
  • 2. Who am I ? Laurent Duveau • I live in Montreal, Canada • Founder of the Angular Academy • 2-day Angular Classroom Training • 152 classes in the last 3 years! • @LaurentDuveau
  • 3. Who am I ? Laurent Duveau • I live in Montreal, Canada • Founder of the Angular Academy • 2-day Angular Classroom Training • 152 classes in the last 3 years! • @LaurentDuveau I LOVE ANGULAR!
  • 4. Angular Router Client-Side Routing Navigate between views in a SPA just like you navigate pages in a normal site Refresh the page and keep the location in app Bookmark the URL, share it with others Works with Browsers back/forward history
  • 6. Sample project Products Module App Module const routes: Routes = [ {path: '', redirectTo:'/home', pathMatch:'full'}, {path: 'home', component: HomeComponent}, {path: 'contact', component: ContactComponent}, ]; const routes: Routes = [ { path: 'products', component: ProductsComponent, children: [ { path: '', component: ProductListComponent }, { path: 'insert', component: ProductInsertComponent }, { path: ':id', component: ProductDetailComponent } ] } ];
  • 9. Lazy Loading ? Loading a module later Better startup performance The delay is during the loading on demand Happens with the Router!
  • 10. Lazy load the Products Module! const routes: Routes = [ {path: '', redirectTo:'/home', pathMatch:'full'}, {path: 'products', loadChildren:'./products/products.module#ProductsModule'}, {path: 'home', component: HomeComponent}, {path: 'contact', component: ContactComponent}, ]; app.routing.ts
  • 11. New syntax coming with Angular V8 and Ivy! const routes: Routes = [ {path: '', redirectTo:'/home', pathMatch:'full'}, {path: 'products', loadChildren:'./products/products.module#ProductsModule'}, {path: 'products', loadChildren: () => import('./products/products.module').then(m => m.ProductsModule)}, {path: 'home', component: HomeComponent}, {path: 'contact', component: ContactComponent}, ]; app.routing.ts Old syntax still here for non-ivy or Angular 7 and below Using dynamic import (new web standard) the new rendering pipeline Well… use one syntax or the other, not both together!
  • 12. Make its routes relative to ‘products/‘ products.routing.ts products.routing.ts const routes: Routes = [ { path: 'products', component: ProductsComponent, children: [ { path: '', component: ProductListComponent }, { path: 'insert', component: ProductInsertComponent }, { path: ':id', component: ProductDetailComponent } ] } ]; const routes: Routes = [ { path: '', component: ProductsComponent, children: [ { path: '', component: ProductListComponent }, { path: 'insert', component: ProductInsertComponent }, { path: ':id', component: ProductDetailComponent } products.routing.ts … so we do not want http://mysite.com/products/products We lazy load this module with: http://mysite.com/products
  • 13. Do not import lazy loaded modules! @NgModule({ imports:[BrowserModule, HttpModule, ProductsModule], }) export class AppModule { } app.module.ts @NgModule({ imports:[BrowserModule, HttpModule], }) export class AppModule { } app.module.ts If you leave it here… you’ll get the opposite effect (eager load)
  • 16. Preloading Modules! Preload a lazy-loadable module in the background while the user is interacting with your application When module is needed it might be available immediately This is about anticipation 16
  • 17. Preloading Modules! * Pictures by Victor Savkin – vsavkin.com
  • 18. Preloading Modules! * Pictures by Victor Savkin – vsavkin.com
  • 19. Preloading Modules! * Pictures by Victor Savkin – vsavkin.com
  • 20. Preloading Modules! * Pictures by Victor Savkin – vsavkin.com
  • 21. Preloading Modules! One built-in preloading strategy: PreloadAllModules Create your Custom Preloading Strategy! Class that implements PreloadingStrategy @NgModule({ imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })], exports: [RouterModule], }) export class AppRoutingModule { }
  • 22. Preloading Modules ngx-quicklink (Open source library) Router preloading strategy which automatically downloads lazy-loaded modules associated with all the visible links in the viewport when the browser is idle. 22 https://www.npmjs.com/package/ngx-quicklink
  • 25. Router Events Event Description NavigationStart Navigation starts RoutesRecognized Router parses the URL and the routes are recognized RouteConfigLoadStart Before the Router lazy loads a route configuration RouteConfigLoadEnd After a route has been lazy loaded NavigationEnd Navigation ends successfully NavigationCancel Navigation is canceled. This is due to a Route Guard returning false during navigation NavigationError Navigation fails due to an unexpected error + more…
  • 26. Router Events 26 @Component({ selector: 'my-app', template: `<router-outlet></router-outlet>` }) export class AppComponent { constructor(private router: Router) {} ngOnInit() { this.router.events .subscribe((event) => { if (event instanceof NavigationEnd) { console.log('NavigationEnd:', event); } }); } }
  • 28. Activate Router traces @NgModule({ imports: [RouterModule.forRoot(routes, { enableTracing: environment.production ? false : true } )] }) export class AppRoutingModule { } app-routing.module.ts
  • 31. Auxiliary Routes Navigation happens in a <router-outlet></router-outlet> We can have more than one! So we can navigate to several routes at the same time!
  • 32. Auxiliary Routes Create a named router-outlet Add a route to target this outlet Link to navigate to the outlet <router-outlet></router-outlet> <router-outlet name="side"></router-outlet> {path:'contact', component:ContactComponent, outlet:'side'} <a [routerLink]="[{outlets: {side:['contact']}}]">Contact</a>
  • 35. Animations Define animations files import { trigger, animate, transition, style } from '@angular/animations'; export const fadeInAnimation = // trigger name for attaching this animation to an element using the [@triggerName] syntax trigger('fadeInAnimation', [ // route 'enter' transition transition(':enter', [ // css styles at start of transition style({ opacity: 0 }), // animation and styles at end of transition animate('.5s', style({ opacity: 1 })) ]), ]); fade-in.animation.ts
  • 36. Animations Import BrowserAnimationsModule Use in @Component decorator @Component({ selector: 'app-product-list’, animations: [fadeInAnimation], host: { '[@fadeInAnimation]': ''} }) export class MyComponent { animation to use attached to host to run animation when component is activated
  • 39. Routes Guards CanActivate CanDeactivate NavigationNavigation Component Decides if a route can be activated - User logged-in ? Decides if a route can be deactivated - Form saved ?
  • 40. Routes Guards 40 export class LoginRouteGuard implements CanActivate { constructor( private loginService: LoginService, private router: Router) {} canActivate() { if(!this.loginService.isLoggedIn()) { this.router.navigateByUrl("/login"); return false; } return true; } } login-route-guard.service.ts { path: 'admin', component: AdminComponent, canActivate: [LoginRouteGuard] }, app-routing.module.ts
  • 42. #8 Passing data via state object during navigation (new in 7.2) 42
  • 43. Passing Data between Routes Setting the State @Component({ template: `<a (click)="navigateWithState()">Go</a>`, }) export class AppComponent { constructor(public router: Router) {} navigateWithState() { this.router.navigateByUrl('/123', { state: { hello: 'world' } }); } } @Component({ selector: 'my-app', template: ` <a routerLink="/details" [state]="{ hello: 'world' }">Go</a>`, }) export class AppComponent {} Imperative navigation Declarative navigation OR
  • 44. Passing Data between Routes Reading the State @Component({ selector: 'app-details-page', template: '<pre>{{ state$ | async | json }}</pre>' }) export class DetailsPageComponent implements OnInit { state$: Observable<object>; constructor(public activatedRoute: ActivatedRoute) {} ngOnInit() { this.state$ = this.activatedRoute.paramMap .pipe(map(() => window.history.state)) } }
  • 47. Route Resolver Pre-fetching component data before navigating Avoid a blank component while waiting for the data to be returned from the server Pre-fetch data from the server so it's ready the moment the route is activated! Create a service and implement the Resolve interface