Generate Routing Application using Angular CLI

  • Install Angular CLI, Node.js and npm to set up the development environment. Refer the below post to set up the environment.

How to install Angular CLI?

  • Create a new workspace and generate a new Routing application by running the following command in command prompt

ng new routingApp –routing

routingApp

Get your popcorn’s as it takes some time to install the npm packages.

  • Generate 3 different components ‘Home’, ‘About Us’ and ‘Contact Us’ in the application.
ng g c home
ng g c aboutUs
ng g c contactUs

routingComponents

  • To configure the corresponding routes, first update src/app/app-routing.module.ts as shown below and import the components
import { HomeComponent } from "app/home/home.component";
import { AboutUsComponent } from "app/about-us/about-us.component";
import { ContactUsComponent } from "app/contact-us/contact-us.component";
const routes: Routes = [
 {path: '', redirectTo:'/home', pathMatch:'full'},
 {path: 'home', component: HomeComponent},
 {path: 'aboutUs', component: AboutUsComponent},
 {path: 'contactUs', component: ContactUsComponent}
];

Next update the app.component.html to different routes as shown below:

<nav>
 <ul>
 <li><a routerLink="/home">Home</a></li>
 <li><a routerLink="/aboutUs">About Us</a></li>
 <li><a routerLink="/contactUs">Contact Us</a></li>
 </ul>
</nav>

<router-outlet></router-outlet>
  • To serve the application run the command
ng serve -o

ng serve routing

routingApp1
This is how the application looks like, happy coding!

One comment

Leave a Reply to AnonymousCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.