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

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 AppKaty Slemon
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Knoldus Inc.
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2Dhyego Fernando
 
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 developersPaweł Żurowski
 
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??Laurent Duveau
 
Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Minko Gechev
 
Beyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and moreBeyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and moreAri Lerner
 
Docker - An Introduction
Docker - An IntroductionDocker - An Introduction
Docker - An IntroductionKnoldus Inc.
 
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...Katy Slemon
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersLaurent Duveau
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next FrameworkCommit University
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?jbandi
 
Angular, the New Angular JS
Angular, the New Angular JSAngular, the New Angular JS
Angular, the New Angular JSKenzan
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training Patrick Schroeder
 
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 levelAnuradha Bandara
 
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 projectFabio Collini
 

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!

Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And NavigationEyal Vardi
 
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.0Frost
 
Web components with Angular
Web components with AngularWeb components with Angular
Web components with AngularAna Cidre
 
Angular2RoutingSetupByShubham
Angular2RoutingSetupByShubhamAngular2RoutingSetupByShubham
Angular2RoutingSetupByShubhamShubham Verma
 
ngNewRouter
ngNewRouterngNewRouter
ngNewRouterphidong
 
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.pdfKaty Slemon
 
Routing in NEXTJS.pdf
Routing in NEXTJS.pdfRouting in NEXTJS.pdf
Routing in NEXTJS.pdfAnishaDahal5
 
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.0Takuya Tejima
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2Paras Mendiratta
 
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.pdfsunilkhetpal
 
Angular resolver tutorial
Angular resolver tutorialAngular resolver tutorial
Angular resolver tutorialKaty Slemon
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applicationsTomek Sułkowski
 
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 ServicesDavid Giard
 
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)Kasper Reijnders
 
Neoito — Routing and navigation in Angular
Neoito — Routing and navigation in AngularNeoito — Routing and navigation in Angular
Neoito — Routing and navigation in AngularNeoito
 
Aurelia Meetup Paris
Aurelia Meetup ParisAurelia Meetup Paris
Aurelia Meetup ParisAhmed Radjdi
 
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 serverSpike 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

Shit happens… debugging an Angular app.
Shit happens… debugging an Angular app.Shit happens… debugging an Angular app.
Shit happens… debugging an Angular app.Laurent Duveau
 
De 0 à Angular en 1h30! (french)
De 0 à Angular en 1h30! (french)De 0 à Angular en 1h30! (french)
De 0 à Angular en 1h30! (french)Laurent Duveau
 
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)Laurent Duveau
 
Debugging an Angular App
Debugging an Angular AppDebugging an Angular App
Debugging an Angular AppLaurent Duveau
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersLaurent Duveau
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersLaurent Duveau
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersLaurent Duveau
 
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 DevelopersLaurent Duveau
 
Introduction à Angular 2
Introduction à Angular 2Introduction à Angular 2
Introduction à Angular 2Laurent Duveau
 
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 webLaurent Duveau
 
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 webLaurent Duveau
 
Introduction to SPAs with AngularJS
Introduction to SPAs with AngularJSIntroduction to SPAs with AngularJS
Introduction to SPAs with AngularJSLaurent Duveau
 
Xamarin.Forms [french]
Xamarin.Forms [french]Xamarin.Forms [french]
Xamarin.Forms [french]Laurent Duveau
 
Back from Xamarin Evolve 2014
Back from Xamarin Evolve 2014Back from Xamarin Evolve 2014
Back from Xamarin Evolve 2014Laurent Duveau
 
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]Laurent Duveau
 
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éveloppeursLaurent 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

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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, Adobeapidays
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

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