Angular 10 Tutorial - Routing
In this tutorial, we will learn about Routing in Angular 10. In Angular, the Router module handles navigation and routing, allowing you to move from one part of the application to another part or from one view to another view.
Creating Components for Routing
So, let's see how we can use the Router in Angular 10. First, create some components. Switch to the command prompt and run the command:
ng g c components /home
ng g c components /about
ng g c components /contact
Okay, now all three components have been created.
Configuring Routing
Now, switch to the project and open the app-routing.module.ts file. Here, import the components:
import {HomeComponent} from './component/home';
import {AboutComponent} from './component/about';
import {ContactComponent} from './component/contact';
Now, create a route by writing inside this array:
const routes: Routes = [
{
path:'home',
component: HomeComponent.
},
{
path:'about',
component: AboutComponent.
},
{
path:'contact',
component: ContactComponent.
},
];
Adding Navigation Bar
Now, go to the app.component.html file and add the Bootstrap navigation bar. So, just go to the Bootstrap website, click on documentation, search for "navbar", and copy the navbar code. Paste it into the app.component.html file and make some changes:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" routerLink="home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="contact">Contact</a>
</li>
</ul>
</div>
</nav>
Don't forget to add the <router-outlet></router-outlet> tag.
Testing Routing
Alright, all done! Let's check. Switch to the browser, and here you can see the navigation bar. Now, click on "Home". You can see the home component content. Now, click on "About". You can see the about content. If I click on "Contact", you can see the contact component content. So, in this way, you can use routing in Angular 10.