Angular Router Introduction 🎯

beginner
9 min

Angular Router Introduction 🎯

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).

What is Angular Router? 📝

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.

Why Use Angular Router? 💡

  • Navigate between different views
  • Manage URLs and handle multiple routes
  • Load dynamic content based on user actions
  • Improve application's navigation and user experience

Getting Started 🎯

Let's begin by installing the Angular Router:

bash
ng add @angular/router

Now, let's create two components: HomeComponent and AboutComponent.

bash
ng generate component home ng generate component about

Creating Routes 📝

Open the app-routing.module.ts file and define the routes:

typescript
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:

  1. '' (empty string) redirects to home route.
  2. home displays the HomeComponent.
  3. about displays the AboutComponent.

Setting Up Navigation 💡

Now, let's create navigation links in the app.component.html file:

html
<nav> <a routerLink="/home">Home</a> <a routerLink="/about">About</a> </nav> <!-- Router Outlet will render the active component --> <router-outlet></router-outlet>

Running the Application ✅

Finally, let's run the application:

bash
ng serve

Now, navigate between the Home and About components using the links we've created.

Advanced Examples 💡

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.

Quiz 🎯

Quick Quiz
Question 1 of 1

What does Angular Router help manage in an Angular application?

Quick Quiz
Question 1 of 1

Why do we use Angular Router?