Back to course

Setting up the Angular Router

The Complete Angular Developer: From Zero to Hero

31. Setting up the Angular Router

Routing is essential for SPAs, allowing navigation between different views without requiring a full page refresh. Angular's router maps browser URLs to application states and displays component views.

Router Setup (If not done during ng new)

When using ng new, the CLI creates app-routing.module.ts and imports RouterModule.forRoot() into the AppModule.

app-routing.module.ts:

typescript import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router';

// 1. Define the Routes array const routes: Routes = [ // Route configurations will go here ];

@NgModule({ imports: [RouterModule.forRoot(routes)], // Configure router at the root level exports: [RouterModule] }) export class AppRoutingModule { }

The Base URL and Router Outlet

Angular needs a place in the main index.html file to determine the base path (if not using the default /). This is usually configured by the build system, but visible as:

html

The <router-outlet> Tag

This is the most critical element. It tells Angular where to display the component associated with the current URL route. You typically place this in app.component.html.

html

...