Routing

  • Configure the routes
  • Add a router outlet
  • Add links

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './components/pages/about/about.component';
import { ContactComponent } from './components/pages/contact/contact.component';
import { HomeComponent } from './components/pages/home/home.component';
import { ServicesComponent } from './components/pages/services/services.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'services', component: ServicesComponent },
  { path: 'contact', component: ContactComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { AboutComponent } from './components/pages/about/about.component';
import { ContactComponent } from './components/pages/contact/contact.component';
import { ServicesComponent } from './components/pages/services/services.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HeaderComponent,
    AboutComponent,
    ServicesComponent,
    ContactComponent,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

mock-data.service.ts

import { Injectable } from '@angular/core';
import { MockHeader } from '../components/header/header.mock';

@Injectable({
  providedIn: 'root',
})
export class MockDataService {
  constructor() {}

  getMockData() {
    return MockHeader;
  }
}

header.component.html

<header class="header">
  <div class="container">
    <div class="header-logo">Logo</div>
    <nav class="header-nav">
      <ul class="header-nav-list">
        <li
          *ngFor="let item of mockData; let i = index"
          class="header-nav-list-item"
        >
          <a
            routerLink="{{ item.url }}"
            routerLinkActive="active"
            class="header-nav-list-item-link"
            >{{ item.title }}</a
          >
        </li>
      </ul>
    </nav>
  </div>
</header>

app.component.html

<router-outlet></router-outlet>

header.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IHeader } from './header.definitions';
import { MockDataService } from 'src/app/services/mock-data.service';
import { AppRoutingModule } from 'src/app/app-routing.module';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [CommonModule, AppRoutingModule],
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
  mockData?: IHeader[];

  constructor(private mockDataService: MockDataService) {}

  ngOnInit() {
    this.mockData = this.mockDataService.getMockData();
  }
}

header.definitions.ts

export type IHeader = {
  id?: string;
  title?: string;
  url?: string;
};

header.mock.ts

import { IHeader } from './header.definitions';

export const MockHeader: IHeader[] = [
  {
    id: '1',
    title: 'Home',
    url: 'home',
  },
  {
    id: '2',
    title: 'About',
    url: 'about',
  },
  {
    id: '3',
    title: 'Services',
    url: 'services',
  },
  {
    id: '4',
    title: 'Contact',
    url: 'contact',
  },
];

Navigating the router links

When applied to an element in a template, makes that element a link that initiates navigation to a route. Navigation opens one or more routed components in one or more <router-outlet> locations on the page.

<ul class="nav">
    <li *ngFor="let item of headerData.menuItems">
        <a routerLink="{{item.slug}}" class="nav-link">
            {{item.name}}
        </a>
    </li>
  </ul>

header.component.ts

headerData = {
    menuItems: [
      { id: 1, name: '/' },
      { id: 2, name: 'About' },
      { id: 3, name: 'Services' },
      { id: 4, name: 'Contact' }
    ],
};

RouterLinkActive directive

Add active class to current menu item

Tracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active.

routerLinkActive="active"

Full snippet

<ul class="nav">
    <li 
      *ngFor="let item of headerData.menuItems"
      routerLinkActive="current-menu-item"
      [routerLinkActiveOptions]="{exact: true}">
        <a routerLink="{{item.slug}}">{{item.name}}</a>
    </li>
</ul>

Inject router into a button

HTML

<button (click)="contactUs()">Contact Us</button>

TS

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

constructor( private router: Router ) { }

contactUs(){
    this.router.navigate(['/contact']);
}

Full snippet

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor( private router: Router ) { }

  ngOnInit(): void {}

  contactUs(){
    this.router.navigate(['/contact']);
  }
}
Was this page helpful?