How To Setup Routing In Angular

How To Setup Routing In Angular

In this article, we will learn the implementation step by step of the routing in the angular application.

Here is an example of how to configure the routing in an angular application

So let's start with implementation

Step 1

Import the necessary angular modules,

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

Step 2

Define its routes as a variety of objects with a route and property of components,

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 the decorator @ngmodule of its application using the lining method,

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Stage 4

Use the directive's router in the HTML of your application to show the components rise,

<router-outlet></router-outlet>

And that is! When the user sails to a URL that matches one of their routes, the corresponding component will be displayed.

Here is the full 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>

Conclusion

In this article, we learned about the Routing In Angular and how to setup in angular application.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post