Welcome Guest! (App Version 3.1)

websitnero logo name

Setting up Routes

Setting up Routes in Angular

To set up routes we need to import the RouterModule and then set up the routes in the app.module.ts file. Later we use the routerLink and routerLinkActive for navigation and adding class to the selected link.

Practical Example of "Setting up Routes"

Please follow the mentioned steps:

  1. Create 3 compennts named 'home', 'about' and 'contact'.

  1. Import the RouterModule in the app.module.ts and make entry in the imports array. Further set the routings in the imports section for Routing in the same file as explained below.
  2. Create some hyperlinks in the app.component.html file. Remember using [routerLink] here instead of href attribute. Also, remember adding routerLinkActive attribute to add some class for the selected link in routing.
  3. In the global file for styling in Angular App -- style.css add a class (I've used as 'selected') to add some styling for whichever link is active in router links.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
import { ContactComponent } from './components/contact/contact.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      {path:'', component: HomeComponent},
      {path:'home', component: HomeComponent},
      {path:'about', component: AboutComponent},
      {path:'contact', component:ContactComponent}
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<ul>
  <li><a [routerLink]="'/home'" routerLinkActive="selected">Home</a></li>
  <li><a [routerLink]="'/about'" routerLinkActive="selected">About</a></li>
  <li><a [routerLink]="'/contact'" routerLinkActive="selected">Contact</a></li>
</ul>

<router-outlet></router-outlet>

app.component.css

.selected {background:orange;}
  1. You'll get the following result.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.