Routing in Angular
Routing is what makes it possible to navigate between different parts of your Angular application like pages or sections without reloading the entire webpage.
This helps create a smooth, app-like experience in your browser.
This helps create a smooth, app-like experience in your browser.
Why Routing Is Important
Better User Experience:
Users can move between different sections of your app (like Home, About, User) instantly, just like a real website.
Better Organization:
Helps you divide your app into multiple views or pages, which makes your code cleaner and easier to manage.
Unique URLs:
Each route can have its own URL, so users can bookmark or share specific pages.
Lazy Loading:
Angular can load parts of your app only when needed, making the first load faster.
Better User Experience:
Users can move between different sections of your app (like Home, About, User) instantly, just like a real website.
Better Organization:
Helps you divide your app into multiple views or pages, which makes your code cleaner and easier to manage.
Unique URLs:
Each route can have its own URL, so users can bookmark or share specific pages.
Lazy Loading:
Angular can load parts of your app only when needed, making the first load faster.
Example: Creating Routes in Angular
Step 1: Create a New Angular Project
ng new routing
Step 2: Create Components
Create three components: home, about and user.
ng g c home
ng g c about
ng g c user
Step 3: Add Navigation Links
Edit app.component.html
<h1>Routing Example</h1><div class="container"> <a routerLink="">Home</a> <pre></pre> <a routerLink="about">About</a> <pre></pre> <a routerLink="user">User</a></div>
<router-outlet></router-outlet>
- routerLink helps users navigate to different components.
<router-outlet> is where the selected component is displayed.
Step 4: Define Routes
Edit app-routing.module.ts
import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { HomeComponent } from './home/home.component';import { AboutComponent } from './about/about.component';import { UserComponent } from './user/user.component';
const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'user', component: UserComponent }];
@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { }
This tells Angular
Step 5: Add Basic Styling
Edit app.component.css
- When the URL is /about, show the AboutComponent.
- When the URL is /user, show the UserComponent.
- When the URL is empty (/), show the HomeComponent.
Step 5: Add Basic Styling
Edit app.component.css
h1 { text-align: center;}
div { text-align: center;}
Step 6: Run Your App
ng serve
Open your browser and go to:
http://localhost:4200
Now, clicking on “Home,” “About,” or “User” shows different views without reloading the page!
Now, clicking on “Home,” “About,” or “User” shows different views without reloading the page!