Introduction
Before we learn angular router basic, we need to know the followings:
- Basic knowledge of Angular
- Setup of a local development environment. You will need Angular CLI to set up your environment.
We will discuss about angular router in this article.Routing is the only method or module that can be used for navigating from one page to another in a Single Page Application. So, let us get started with Angular Router Tutorial.
Setup New Angular Project
Install Angular CLI globally on your system by typing the following command.
npm install -g @angular/cli
Now, create one project called angular-router.
ng new angular-router
Generate Components
Now we need to generate three components using command below.
ng generate component home
ng generate component about
ng generate component contact
Configuration – How to use Angular Router ?
After the components are generated, we need to configure them in app.routing.module.ts.
Replace the code in app.routing.module.ts by code below.
Also learn about Component Life Cycle Hooks in Angular
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {AboutComponent} from './about/about.component';
import {ContactComponent} from './contact/contact.component';
import {HomeComponent} from './home/home.component';
const routes: Routes = [
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'home', component: HomeComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Herer we have import the components we have created and added them in routes array.
Angular Routing Navigation
Open the app.component.html page replace with code below
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
</h1>
<nav>
<a routerLink="home" routerLinkActive="active">Home</a>
<a routerLink="about">About</a>
<a routerLink="contact">Contact</a>
</nav>
<router-outlet></router-outlet>
</div>
Here we have added <router-outlet> which is used to render our actual page.
Now open the terminal and run ng serve command.
After that goto our web browser and type the url http://localhost:4200 and it will open the page below.
Now when we click on the links,it will navigate us to that particular route.
For example,When we click on about link,we will be navigate to About components and all the contents for that page will be shown.
Conclusion
From this article we have learned about using router in Angular