Set Page Title Using Title Service Angular Example

This tutorial explains how to set the page title using the title service in Angular apps using an example. The title service allows us the change the HTML title of the application with ease.

Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10

Why change page title

Changing the page title is very important as it helps the search engines to know the purpose of the page and index it properly. It also helps users to know, which page they are in.

Being a single page app, the angular does not reload the entire page. The page is loads only once at the startup. Only part of the page gets loaded when you navigate from one route to another.

The title of the page is set in the index.html as shown below. We use the HTML title tag to set the title of the app. Since it is loaded only at the start, all other pages or routes get the same title.

Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10

Title Service in Angular

We can make use of the title service in angular to make changes to the document title

How to Use Title Service

Import it in Angular Module

Note that the title service is part of the platform-browser package. i.e because the title meta tag is applicable to the HTML page in the browser.

If you are using any other platform like NativeScript for mobile apps, you need a different service. The service, which understands the platform.

Register the service with DI Providers

Like all other Angular services, we need to register the title service with the Angular Providers in the root Angular module.

Inject Title service in the component

Inject the title service, like all other Angular Service in the component using Dependency Injection

The title service provides only two methods. SetTitle & GetTitle. We use SetTitle to set the title of the page and GetTitle to find out the current title of the page.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

Use the setTitle method to set the title

That’s it.

Title service example

The following is the example app, which has three components. Each component uses the setTitle method of the Title service to set the title of each component.

app.module.ts

app-routing.module.ts

app.component.ts

app.component.html

one.component.ts

two.component.ts

three.component.ts

Angular Title Service Example

References

Title

Summary

We learned how to make use of Title service in Angular

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top