Header Component with Routing - RouterLinkActive & Active Menu

A header component is created to place the logo and all routing links in one place.

The header stays visible on all pages.

When a menu is clicked, that menu gets highlighted.

Even after page refresh, the active menu remains highlighted.


Creating Header Component

Header component is created using Angular CLI inside a components folder.

Command used:

ng g c components/header

A header component is created inside the components folder.


Using Header Component in App

Header component is imported into the main app file and used in the app HTML.

import { HeaderComponent } from './components/header/header.component';


<app-header></app-header>


Moving Menu Links to Header

The routing menu links are moved from app.html to header.html.

Now all navigation is handled from the header component.


Router Links in Header Component

Since routing links are used in the header, RouterLink must be imported in header.ts.

import { RouterLink } from '@angular/router';

RouterLink is removed from app.ts because it is no longer needed there.


Header HTML Structure


<div class="header">
<h3>App</h3>

<ul>
<li><a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a></li>
<li><a routerLink="/login" routerLinkActive="active">Login</a></li>
<li><a routerLink="/about" routerLinkActive="active">About</a></li>
<li><a routerLink="/profile" routerLinkActive="active">Profile</a></li>
</ul>
</div>


Header Styling (CSS)


.header {
display: flex;
justify-content: space-between;
}

.header ul {
display: flex;
list-style-type: none;
}

.header ul li {
padding: 5px 10px;
}

.header ul li a {
text-decoration: none;
color: orange;
}

.active {
color: red;
text-decoration: underline;
}


RouterLinkActive

routerLinkActive is used to apply an active class on the current menu.

This makes the clicked menu highlighted automatically.


Exact Match for Home Route

Home route uses an empty path, so it stays active by default.

To fix this, routerLinkActiveOptions with exact: true is used.

[routerLinkActiveOptions]="{ exact: true }"

Now only the correct menu is highlighted.