In this article, we will learn step-by-step implementation of routing in the angular application.
Here's an example of how to set up routing in an Angular application
Step 1
Import the necessary Angular modules,
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
Step 2
Define your routes as an array of objects with a path
and component
property,
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
];
Step 3
Add the routes to your app's @NgModule
decorator using the forRoot
method,
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 4
Use the router-outlet
the directive in your app's HTML to display the routed components,
<router-outlet></router-outlet>
And that's it! When the user navigates to a URL that matches one of your routes, the corresponding component will be displayed.
Here's the complete example,
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
import { ContactComponent } from './contact.component';
const routes: Routes = [{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}, {
path: 'home',
component: HomeComponent
}, {
path: 'about',
component: AboutComponent
}, {
path: 'contact',
component: ContactComponent
}, ];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
<!-- app.component.html -->
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/contact">Contact</a>
</nav>
<router-outlet></router-outlet>
I hope this helps. If this helps you, then share it with others.
Sharing is caring! :)