NashTech Blog

Setting Page Titles Natively With The Angular Router

Table of Contents
template

In the world of web development, creating a seamless and engaging user experience is crucial. One aspect often overlooked is setting appropriate and dynamic page titles. Page titles are essential for search engine optimization (SEO) and for providing users with context about the content they are viewing. In Angular, setting page titles natively with the Angular Router is a powerful way to achieve this. In this blog post, we will explore how to do just that.

The Importance of Page Titles

Page titles are not just a cosmetic aspect of your website; they play a significant role in user experience and SEO. Here’s why they matter:

  1. User Experience: Page titles give users a quick summary of the content on a page. This helps them understand where they are within your website and what to expect from the content.
  2. SEO: Search engines use page titles to understand the relevance of a web page to a user’s search query. Well-structured and meaningful page titles can boost your website’s ranking in search results.

Setting Static Page Titles

In Angular, setting static page titles is straightforward. You can set the title directly in your HTML file using the <title> tag. However, this approach doesn’t allow for dynamic page titles based on the current route or component.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My Static Page Title</title>
  </head>
  <body>
    <!-- Your Angular app content -->
  </body>
</html>

To set dynamic page titles that change according to the current route or component, we’ll utilize Angular’s Router module.

Dynamic Page Titles with Angular Router

To set dynamic page titles, you need to interact with the Angular Router. Angular Router provides an easy way to access the current route and its associated data. Here’s how you can achieve this:

1. Install Angular Router

If you haven’t already, make sure to set up the Angular Router in your project. You can do this using the Angular CLI:

ng generate module app-routing --flat --module=app

This command will create an app-routing.module.ts file and configure the basic routes for your application.

2. Configure Routes

In your routing module, define your routes and specify a data property for each route. This data property can contain metadata, including the title of the page.

const routes: Routes = [
  { path: '', component: HomeComponent, data: { title: 'Home' } },
  { path: 'about', component: AboutComponent, data: { title: 'About Us' } },
  { path: 'contact', component: ContactComponent, data: { title: 'Contact Us' } },
];

3. Set the Dynamic Title

Now, in your app component or a custom title service, you can subscribe to the router events and update the page title based on the current route data.

import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css',
})
export class AppComponent {
  constructor(private titleService: Title, private router: Router) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        const title = this.getTitle(this.router.routerState, this.router.routerState.root).join(' | ');
        this.titleService.setTitle(title);
      }
    });
  }

  private getTitle(state: any, parent: any): string[] {
    const data = [];
    if (parent && parent.snapshot.data && parent.snapshot.data.title) {
      data.push(parent.snapshot.data.title);
    }

    if (state && parent) {
      data.push(...this.getTitle(state, state.firstChild(parent)));
    }

    return data;
  }
}

In this code, we subscribe to the router events and update the page title whenever a navigation event occurs. We extract the route data using the data property and concatenate it to create a meaningful page title.

Benefits of Setting Page Titles Natively with Angular Router

Setting page titles natively with the Angular Router offers several advantages:

  1. Dynamic Titles: Page titles are dynamic and change according to the current route and component, enhancing the user experience.
  2. SEO Optimization: Having meaningful and relevant page titles improves your website’s SEO, as search engines can better understand your content.
  3. Consistency: Centralizing title-setting logic makes it easier to maintain a consistent and unified approach across your application.
  4. Accessibility: Screen readers and other assistive technologies benefit from descriptive page titles that provide context.

Conclusion

In web development, the devil is often in the details, and page titles are no exception. Setting page titles natively with the Angular Router is a powerful way to enhance user experience, improve SEO, and ensure that your website is accessible to all users. By following the steps outlined in this blog post, you can create dynamic and meaningful page titles for your Angular application, setting it on the path to success.

For more such posts, please follow our LinkedIn page- FrontEnd Competency.

Picture of Neha

Neha

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top