Author avatar

Parul Saxena

Styling Links with routerLinkActive in Angular

Parul Saxena

  • Jun 26, 2020
  • 9 Min read
  • 428 Views
  • Jun 26, 2020
  • 9 Min read
  • 428 Views
Languages Frameworks and Tools
Front End Web Developer
Client-side Frameworks
Angular

Introduction

When you have multiple links in the top navigation bar of your app, it is important for the end user to be able to differentiate between the active link they have selected and inactive links. This differentiation can be achieved by showing the active link in a different color and style. In Angular, you can do this using an out-of-the-box directive called routerLinkActive.

In this guide, you will learn how to use the routerLinkActive directive to show the active link in a different color and style. You will create a demo app with a navigation bar with links to two routes of the application. To complete this guide, you must have the following:

  1. Node - 12.17.0
  2. Angular CLI - 9.0.2
  3. Visual Studio Code - 1.45.1

Getting Started

Create an Angular Project

  1. Execute the following command to create an Angular project.

ng new active-route-demo

  1. When prompted to add routing to the application press 'N'.
  2. When prompted to choose stylesheet format press 'ENTER'.

Opening the Generated Application in Visual Studio Code

  1. Click on the File menu in the top menu bar and select the menu option Open Folder.
  2. In the file dialog box, navigate to the folder where you generated the application.
  3. In this folder, you should see a folder named active-route-demo. Select this folder and click Open in the file dialog box.

Setting Up the Project

The next step is to install Twitter Bootstrap and jQuery and reference them in the project.

  1. Go to command prompt and run following command:

cd active-route-demo

  1. Run the following command to install jquery:

npm i jquery

  1. Run the following command to install Bootstrap:

npm i bootstrap

  1. In Visual Studio Code, open the file angular.json.
  2. Add the following line in the styles array before src/style.css.

"node_modules/bootstrap/dist/css/bootstrap.min.css",

  1. Add the following lines in the scripts array:

"node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js"

  1. In Visual Studio Code, open the file src > index.html.
  2. At line number 10, in the body element, add the following class:

class="container"

The final code should look like this:

1
2
3
<body class="container">  
<app-root></app-root>
</body>

Now the project is all set to develop the demo application.

Setting up the Routing

In Visual Studio Code, open the file src > app > app.module.ts, delete the contents of the file, and add the following code. This code imports Angular's router module and creates a routes array in which you will keep all your application routes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import {RouterModule, Routes} from '@angular/router';


const routes: Routes = [
];


@NgModule({
  declarations: [
    AppComponent,
    NavBarComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Developing the Home Component

  1. Run the following command in the command prompt:

ng generate component home

  1. In Visual Studio Code, open the file src > app > home > home.component.html, delete the contents of the file, and add following code:
1
2
3
4
5
6
7
8
9
10
11
<h1>Home Component</h1>
<pre>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Aliquam sem fringilla ut morbi tincidunt. Feugiat nibh sed pulvinar proin gravida hendrerit. Sed blandit libero volutpat sed cras ornare. 
Est lorem ipsum dolor sit amet consectetur adipiscing. Bibendum at varius vel pharetra vel turpis nunc eget. Vulputate dignissim suspendisse in 
est ante in nibh mauris. Magna fermentum iaculis eu non diam phasellus vestibulum lorem sed. Faucibus in ornare quam viverra orci sagittis eu volutpat. 
Ante metus dictum at tempor commodo ullamcorper a lacus vestibulum. Arcu dictum varius duis at consectetur lorem donec massa. Turpis egestas pretium aenean 
pharetra magna ac placerat. Turpis egestas pretium aenean pharetra magna ac placerat vestibulum. Faucibus scelerisque eleifend donec pretium. Vel turpis nunc 
eget lorem dolor sed viverra ipsum nunc. In fermentum et sollicitudin ac orci. Massa massa ultricies mi quis hendrerit dolor magna eget est. Sem integer vitae 
justo eget magna fermentum iaculis eu. Diam sollicitudin tempor id eu nisl nunc mi ipsum. Nunc consequat interdum varius sit amet mattis.
</pre>

Developing the About Us Component

  1. Run the following command in the command prompt:

ng generate component about-us

  1. In Visual Studio Code, open the file src > app > about-us > about-us.component.html, delete the contents of the file, and add the following code:
1
2
3
4
5
6
7
8
9
10
11
<h1>About Us</h1>
<pre>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Aliquam sem fringilla ut morbi tincidunt. Feugiat nibh sed pulvinar proin gravida hendrerit. Sed blandit libero volutpat sed cras ornare. 
Est lorem ipsum dolor sit amet consectetur adipiscing. Bibendum at varius vel pharetra vel turpis nunc eget. Vulputate dignissim suspendisse in 
est ante in nibh mauris. Magna fermentum iaculis eu non diam phasellus vestibulum lorem sed. Faucibus in ornare quam viverra orci sagittis eu volutpat. 
Ante metus dictum at tempor commodo ullamcorper a lacus vestibulum. Arcu dictum varius duis at consectetur lorem donec massa. Turpis egestas pretium aenean 
pharetra magna ac placerat. Turpis egestas pretium aenean pharetra magna ac placerat vestibulum. Faucibus scelerisque eleifend donec pretium. Vel turpis nunc 
eget lorem dolor sed viverra ipsum nunc. In fermentum et sollicitudin ac orci. Massa massa ultricies mi quis hendrerit dolor magna eget est. Sem integer vitae 
justo eget magna fermentum iaculis eu. Diam sollicitudin tempor id eu nisl nunc mi ipsum. Nunc consequat interdum varius sit amet mattis.
</pre>

Developing the Navigation Bar

  1. Run the following command in the command prompt:

ng generate component nav-bar

  1. In Visual Studio Code, open the file src > app > nav-bar > nav-bar.component.html, delete the contents of the file, and add the following code. In this code, notice that the routerLinkActive directive is applied on the anchor tag. This directive takes a CSS class as a parameter, which renders the link in a different color and style. Also notice the property routerLinkActiveOptions. This property ensures that the route is shown in a different color only when the route completely matches the routes that you declared in the app.module.ts file earlier.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<nav class="navbar navbar-expand-sm bg-dark">
    <ul class="nav navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">Router Outlet Demo</a>
        </li>
        <li class="nav-item">
            <a [routerLink]="['/home']" class="nav-link" routerLinkActive="active"
                [routerLinkActiveOptions]="{exact:true}">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" [routerLink]="['/about']" routerLinkActive="active">About</a>
        </li>
    </ul>
</nav>
  1. In Visual Studio Code, open the file src > app > nav-bar > nav-bar.component.css and add the following code:
1
li > a.active { color: #F97924 }

Setting up the Routes

  1. In Visual Studio Code, open the file src > app > app.module.ts.
  2. In the routes array, add the following entries:
1
2
{path:'home', component: HomeComponent},
{path:'about', component: AboutUsComponent}

Using the router-outlet Component

In Visual Studio Code, open the file src > app > app.component.html, delete existing content, and add the following code to add the router-outlet component to the mix so that different routes are rendered in it.

1
2
<app-nav-bar></app-nav-bar>
<router-outlet></router-outlet>

Testing the Application

You are now ready to run the RouterLinkActive directive.

  1. Run the following command in the command prompt to start Angular Development Server in watch mode:

ng serve

  1. If prompted to share Angular CLI usage data, press the 'N' key to not share it.
  2. Open a browser and type the following URL in the address bar to launch the application: http://localhost:4200.
  3. Notice that there are two links in the navigation bar: Home and About.
  4. Click on the About link and notice the display below the navigation bar changes, showing the HTML of the About-us component.
  5. Click back on the Home link and notice the display below the navigation bar changes, showing the HTML of the Home component.

Conclusion

Congratulations!! You have learned how to use the routerLinkActive directive to show the active link to the user. For more information, please visit RouterLinkActive Directive.

4