Dynamic Page Title In Angular 9

Recently while working on Angular 9 project with SharePoint rest API, I came across this requirement where I needed to set the SharePoint List name as page title in Angular 9. We were developing a generic application wherein through Configuration, the entire SharePoint list data would be displayed to the UI. The configuration will hold information which columns from SharePoint needs to be displayed on UI, LIST name etc. It’s been a generic application, we just have to tune the Configuration file & it would start working for any SharePoint list. As my Anguar application depends on this file setting, so even before my Angular application starts I need to load this configuration file.
 
I’d used APP_INITIALIZER for my application to seed the configuration file.
 
We set the page title in index.html file inside the head section of our html page, which is not where our Angular is instantiated.
  1. <head>  
  2.    <meta charset="utf-8">  
  3.       <title></title>  
  4.       <base href="/">  
  5.    <meta name="viewport" content="width=device-width, initial-scale=1">  
  6. <link rel="icon" type="image/x-icon" href="favicon.ico">  
  7. </head>  
Our Angular scope starts as soon as our AppComponent is instantiated which is declared as an element inside the Body section of our index.html page with selector <app-root>
  1. <body>  
  2.    <app-root></app-root>  
  3. </body>  
There are various scenarios wherein you could come across this scenario of dynamically setting the page title. Some of the examples would be change the page title on click of link on page, or you’re getting some configuration/page settings from some external api call etc.
 
How can we set the page title dynamically? For handling this scenario Angular provides us with a Title service – which helps us to get or set the page title. This service just provides two methods; i.e. setting the page Title & getting the page Title. Title service is a part of @angular/platform-browser package. Since Title is a service we’ll have to import it as a Provider inside our app.module.ts file.
 
For demonstration purposes of this article, we would consider the page title is coming from configuration file which is under the assets folder within our application. Here is the code snippet of our app-config.json file. For simplicity sake I’m just having one setting, in your real application you could have many more settings inside your configuration file.
  1. {  
  2.     "settings": [{  
  3.         "key""PAGE_TITLE",  
  4.         "value""DYNAMIC PAGE TITLE"  
  5.     }]  
  6. }  
For a strong typing experience I’ve defined one model for our app-config.json file. Here is the code snippet for Config.model.ts
  1. export class Config {  
  2.     settings: ISettings[];  
  3. }  
  4. export interface ISettings {  
  5.     key: string;  
  6.     value: string;  
  7. }  
I’ve defined one AppConfig.service.ts file which reads the configuration from our app-config.json file.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { Observable, BehaviorSubject } from 'rxjs';  
  4. import { Config } from '../models/config.model';  
  5. @Injectable()  
  6. export class AppConfigService {  
  7.    readonly appConfiguration$: Observable<Config>;  
  8.    private appConfiguration: BehaviorSubject<Config>;  
  9.    
  10. constructor(private http: HttpClient) {  
  11.    this.appConfiguration = new BehaviorSubject({} as Config);  
  12.    this.appConfiguration$ = this.appConfiguration.asObservable();  
  13. }  
  14. public getAppConfig(): Observable<Config> {  
  15.    return Observable.create((observer) => {  
  16.       this.http.get<Config>('/assets/app-config.json').subscribe((response) => {  
  17.       this.appConfiguration.next(response);  
  18.       return observer.next(response);  
  19.       });  
  20.    });  
  21.  }  
  22. }   
As my application needs this configuration file, I have to load this file inside our APP_INITIALIZER. Here is the code snippet for the same.
  1. import { BrowserModule, Title } from '@angular/platform-browser';  
  2. import { NgModule, APP_INITIALIZER } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  5. import { AppComponent } from './app.component';  
  6. import { AppConfigService } from './services/app-config.service';  
  7.    
  8. @NgModule({  
  9.    declarations: [  
  10.    AppComponent  
  11. ],  
  12. imports: [  
  13.    BrowserModule,  
  14.    HttpClientModule,  
  15.    BrowserAnimationsModule  
  16. ],  
  17. providers: [  
  18.    Title,  
  19.    AppConfigService,  
  20.    {  
  21.       provide: APP_INITIALIZER,  
  22.       useFactory: (appConfigSvc: AppConfigService, titleService: Title) => {  
  23.       return () => {  
  24.          return appConfigSvc.getAppConfig().subscribe((response) => {  
  25.          titleService.setTitle(response.settings.find(x => x.key == 'PAGE_TITLE').value);  
  26.          });  
  27.       }  
  28.    },  
  29.    multi: true,  
  30.    deps: [AppConfigService, Title]  
  31.    }  
  32.   ],  
  33.  bootstrap: [AppComponent]  
  34. })  
  35. export class AppModule { }  
NOTE
If you need to reset the pageTitle on click of a link, you could simply use the below code snippet.
 
titlService.setTitle(‘Your new title goes here’);

Here is the snapshot of our working demo.
 
Dynamic Page Title In Angular 9


Similar Articles