Episode 17 of 27

Adding Links

Navigate with routerLink — create navigation links, active link styling, and router-aware navigation.

Adding Links

In Angular, you don't use regular <a href=""> links for navigation — those cause a full page reload. Instead, use routerLink for client-side navigation.

routerLink Directive

<!-- Static route -->
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/contact">Contact</a>

<!-- Array syntax (for dynamic segments): -->
<a [routerLink]="['/user', userId]">Profile</a>
<!-- Generates: /user/42 -->

Why Not href?

<!-- ❌ Full page reload — defeats SPA purpose -->
<a href="/about">About</a>

<!-- ✅ Client-side navigation — instant, no reload -->
<a routerLink="/about">About</a>

Active Link Styling with routerLinkActive

<nav>
    <a routerLink="/" 
       routerLinkActive="active" 
       [routerLinkActiveOptions]="{ exact: true }">
       Home
    </a>
    <a routerLink="/about" routerLinkActive="active">About</a>
    <a routerLink="/contact" routerLinkActive="active">Contact</a>
</nav>

routerLinkActive automatically adds the CSS class "active" when the link's route matches the current URL.

The exact Option

<!-- Without exact: true, the "/" route is ALWAYS active
     because every URL starts with "/" -->
<a routerLink="/" 
   routerLinkActive="active"
   [routerLinkActiveOptions]="{ exact: true }">
   Home
</a>

Styling Active Links

/* CSS for active navigation */
nav a {
    color: #888;
    text-decoration: none;
    padding: 8px 16px;
    border-radius: 6px;
    transition: color 0.2s, background 0.2s;
}

nav a:hover {
    color: #333;
    background: rgba(0,0,0,0.05);
}

nav a.active {
    color: #3498db;
    background: rgba(52,152,219,0.1);
    font-weight: 600;
}

Full Navbar Example

// header.component.ts
@Component({
    selector: 'app-header',
    template: `
        <header>
            <h1>{{ title }}</h1>
            <nav>
                <a routerLink="/" 
                   routerLinkActive="active"
                   [routerLinkActiveOptions]="{ exact: true }">
                   Home
                </a>
                <a routerLink="/about" routerLinkActive="active">About</a>
                <a routerLink="/contact" routerLinkActive="active">Contact</a>
            </nav>
        </header>
    `
})
export class HeaderComponent {
    title = 'My App';
}

Key Takeaways

  • Use routerLink instead of href for Angular navigation
  • routerLinkActive="class" adds a CSS class when the link's route is active
  • Use { exact: true } on the home route to prevent it from always being active
  • Use array syntax [routerLink]="['/path', param]" for dynamic routes
  • Style the .active class for visual navigation feedback