Routing

  • Routes are defined in a route definition table that in its simplest form contains a path and component reference
  • Components are loaded into the router-outlet directive
  • We can navigate to routes using the routerLink directive
  • The router uses history.pushState which means we need to set a base-ref tag to our index.html file
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AuthGuard } from './shared/guards/auth.guard';

const routes: Routes = [
 { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
 {
    path: 'courses',
    canActivate: [AuthGuard],
    loadChildren: () =>
    import('./courses/courses.module').then((m) => m.CoursesModule),
 }
 { path: '**', redirectTo: '/home' },
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule],
})
export class AppRoutingModule {}

And in the template file:

<mat-sidenav-container>
    <mat-sidenav>
        <nav>
            <a mat-button class="nav-link"
                *ngFor="let link of links"
                [routerLink]="link.path" routerLinkActive="active">
                <mat-icon>
                    {{link.icon}}
                </mat-icon>
                {{link.title}}
            </a>
        </nav>
    </mat-sidenav>
 
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</mat-sidenav-container>

The Angular Router NgModule provides a Services that lets you define a navigation path among the different application states and view hierarchies in your application.

If the router determines that the current application state requires particular functionality, and the module that defines it hasn't been loaded, the router can lazy-load the module on demand.

The router interprets a link URL according to your application's view navigation rules and data state. You can navigate to new views when the user clicks a button or selects from a drop box, or in response to some other stimulus from any source. The router logs activity in the browser's history, so the back and forward buttons work as well.

To define navigation rules, you associate navigation paths with your components. A path uses a URL-like syntax that integrates your program data, in much the same way that template syntax integrates your views with your program data. You can then apply program logic to choose which views to show or to hide, in response to user input and your own access rules.