Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

angular routing

Gregor Woiwode edited this page Dec 9, 2019 · 8 revisions

Lazy Loading

  • Generate a new Module called about

    ng g m about
    
  • Generate a component for AboutModule

    ng g c about/about --flat
    
  • Create a route configuration for AboutModule

    // about/about-routing.module.ts
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { AboutComponent } from './about.component';
    
    const routes: Routes = [{ path: '', component: AboutComponent }];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    export class AboutRoutingModule {}
  • Don't forget to add AboutRoutingModule to AboutModule's imports-List

  • Configure the about page to be loaded when the respective link is activated

    // app-routing.module.ts
    
    const routes: Routes = [
      { path: '', pathMatch: 'full', redirectTo: 'todos/all' },
    + { path: 'about', loadChildren: () => import('./about/about.module').then(m => m.AboutModule) }
    ];
  • Place a link in app.component.html navigating to the About-page

    // app.component.html
    <a routerLink="/about">About</a>
  • Use the Network-Tab of ChromeDevtools to see that about.module is only loaded when the link is clicked or the about/-route is requested directly.

Guards

  • Write a guard that prompts the user to confirm the access for the about/-route

Hints

ng g g about/shared/sure
// sure.guard.ts
canActivate(): boolean {
  return confirm('Are you sure?');
}
// about-routing.module.ts
{ path: '', component: AboutComponent, canActivate: [SureGuard] }
Clone this wiki locally