Welcome to our comprehensive guide on Angular Router! In this tutorial, we'll dive deep into understanding routing in Angular, a powerful tool for building Single Page Applications (SPAs).
Angular Router is a navigation service that enables dynamic content loading based on the user's actions. It helps to manage different components, templates, and URLs in an Angular application.
Let's begin by installing the Angular Router:
ng add @angular/routerNow, let's create two components: HomeComponent and AboutComponent.
ng generate component home
ng generate component aboutOpen the app-routing.module.ts file and define the routes:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }In the above code, we've defined three routes:
'' (empty string) redirects to home route.home displays the HomeComponent.about displays the AboutComponent.Now, let's create navigation links in the app.component.html file:
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<!-- Router Outlet will render the active component -->
<router-outlet></router-outlet>Finally, let's run the application:
ng serveNow, navigate between the Home and About components using the links we've created.
In this tutorial, we've only scratched the surface of Angular Router. To learn more about nested routes, route guards, and parametrized routes, check out our advanced Angular Router tutorials.
What does Angular Router help manage in an Angular application?
Why do we use Angular Router?