Introduction
In this article, I will show the steps 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.
Note. Before going through this session, please visit my previous article related to Angular applications as mentioned below.
Angular Application
Step 1. Create 3 Components using the below command
Each component uses the setTitle method of the Title service to set the title of each component.
Step 2. Add code in app.module.ts
Step 3. Add code in app-routing.module.ts
Step 4. Add code in app.component.ts
Step 5. Add code in app.component.html
Step 6. Add code in one.component.ts
Step 7. Add code in two.component.ts
Step 8. Add code in three.component.ts
Code Setup and the need of the page title
Updating the page title is very important as it helps search engines know the purpose of the page and index it properly. It also helps users to know, which page we are in. As a single-page app, the angular does not reload the entire page. The page loads only once at the startup. Only part of the page gets loaded when you navigate from one route to another route.
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.
What is title service in Angular?
A service that can be used to get and set the title of a current HTML document. Important methods are shown below.
- getTitle(): Get the title of the current HTML document.
- setTitle(): Set the title of the current HTML document.
Steps to use title service
Import it in the Angular Module.
Here 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.
Steps to register the service with DI providers
We need to register the title service with the Angular Providers in the root Angular module in app.module.ts.
Steps to inject title service in the component
Inject the title service, like all other Angular Services in the components (app.component.ts, one.component.ts, two.component.ts, three.component.ts) using Dependency Injection.
setTitle method to set the title in the Angular application
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.
Output
For first-time load, the title is shown below.
![Title server example]()
On selection of the Male link check the title and message.
![Male section]()
On selection of the Female link check the title and message.
![Female section]()
On selection of Unknown link check the title and message.
![Unknown section]()
Summary
In this write-up, we have learned the details below.
- What is Title Service in Angular
- Importance of the page title
- Steps to implement Title service in Angular
Thank You & Stay Tuned For More