Ensure that the dynamically inserted <title> tag remains intact in Angular even when the page is re

Can the dynamic title tag be preserved when the page is refreshed?

When I refresh the page, the title tag reverts back to the original one specified in the index.html temporarily before switching back to the dynamically added one. I want the title tag to remain consistent even during page refresh.

Below is code snippet from my app.component.ts file:

this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.activatedRoute),
      map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      }),
      filter((route) => route.outlet === 'primary'),
      mergeMap((route) => route.data)
    )
      .subscribe((event) => {
        console.log(event)
        this.translateService.get(event['title']).subscribe(name => {
          this._seoService.updateTitle(name);
        });
        this._seoService.updateDescription(event['description'])
      });

Answer №1

If you're looking for a way to store and retrieve dynamic titles, one method is utilizing Local Storage. This simple example demonstrates how to store the title in Local Storage and then display it upon page refresh. Angular offers a convenient service called Title that enables us to dynamically update the title whenever needed.

<button (click)="setItem()">Click to set a title</button>

<p *ngIf="showInfo" >Refresh the page now :)</p>
export class AppComponent implements OnInit {
  showInfo = false;  

  constructor(private titleService: Title) {}

  ngOnInit() {
    this.getItem();
  }

  setItem() {
    localStorage.setItem('title', 'Hey World!');
    this.showInfo = true;
    this.getItem();
  }

  getItem() {
    if (localStorage.getItem('title'))
      this.titleService.setTitle(localStorage.getItem('title'));
    else this.titleService.setTitle('No title');
  }
}

Experience the functionality with this live application.

Code available on Stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

strange complications with importing TypeScript

In my Typescript projects, I frequently use an npm module called common-types (repository: https://github.com/lifegadget/common-types). Recently, I added an enum for managing Firebase projects named FirebaseEvent. Here is how it is defined: export enum Fi ...

When buttons are clicked within Angular Material's Card component, it automatically triggers the click event of the card itself

One of the challenges I'm facing is having a mat-card within a component template: <mat-card *ngFor="let p of products" (click)="viewProduct(p)"> <mat-card-actions> <button mat-stroked-button (click)="addProductToCart(p)"&g ...

Incorporating HTTP headers into Angular 6

Could someone confirm if this method is correct for adding headers to http requests in Angular 6? Upon inspecting the call through SwaggerUI, it appears that the required headers are: url -X GET --header 'Accept: application/json' --header &apo ...

Waiting for a webpage to fully load with JavaScript in Selenium

I am facing an issue where I need to wait for the page to fully load before executing a certain action. It is important for me that the loading circle on the browser tab stops spinning before proceeding. The current Ajax function I am using does not work c ...

Error in Angular Template Parsing Due to Dynamic Object Key in Angular Version Greater Than 2

When I attempt to assign a value for a key with a variable inside my event binding expression, an unexpected error occurs: Parser Error: Unexpected token [, expected identifier, keyword, or string at column... the expression in question is: (ngModelChange ...

Using the data of multiple locations within a for loop to create Leaflet markers for use in a click event

I am currently working on a leaflet map that showcases markers for the top cities in a selected country. The locationList array consists of objects with city information such as latitude, longitude, and cityName. These values are utilized to place markers ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

Passing data to a redirected route in Angular using the redirectTo parameter

Is there a way to send the "data" to the home component only when redirected from an old path, and not from an empty path? const routes: Routes = [ {path : '', redirectTo:'home'}, {path : 'oldPath', redirectTo:&apo ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

Trouble displaying Bar Graph in chart.js using PHP

I am facing a challenge with creating a bar graph using chart.js that loads data from a PHP array via ajax. The data is successfully loaded through ajax, as confirmed in the console, but I am unable to display it on the graph. Here's what I see in the ...

A method to trigger the opening of a div tag when a button is clicked using Vue.js

<div class="input-wrapper"> <div class="mobile-icon"></div> <input class="input-section label-set" type="text" v-model.trim="$v.mobile.$model" :class="{'is-invalid': ...

Interested in transforming and showcasing dates within a MySQL database?

Here's a form with 10 JQuery UI date pickers set up: $(function() { $("#datepicker").datepicker({ minDate: 'today', maxDate: "+90D", showOn: "button", buttonImage: "images/calendar-new2.jpg", buttonImageOnly: true, dateFormat: "D, dd M, yy" ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Learning the process of configuring neo4j connection details without relying on environment variables

Is there a way to specify the database connection in code using the Drivine neo4j driver without relying on environment variables? ...

Establishing the controller to set the default order

Would appreciate some assistance with what may appear to be a beginner's question, please? This is the HTML code I'm working with: <!doctype html> <html> <head> <title>Starting Angular</title> </head> < ...

Can we verify if strings can serve as valid property names for interfaces?

Let's consider an interface presented below: interface User { id: string; name: string; age: number; } We also have a method defined as follows: function getUserValues(properties:string[]):void { Ajax.fetch("user", properties).then( ...

Why does the map function in JavaScript not allow for a function argument?

I encountered an issue while calling a function and passing an array of objects as the first argument, with the second argument being an object property of the first argument. Strangely, the map function was not accepting the second argument property. He ...

AngularJS component downgraded without change detection

Currently, I am utilizing Angular's downgradeComponent for performance optimization purposes. You can find more information about it here: https://angular.io/api/upgrade/static/downgradeComponent. The Angular component I am working with is defined as ...

What could be causing the "Error: InvalidPipeArgument" to appear in my Angular code?

Currently, I am tackling a challenge within my Angular project that involves the following situation: Essentially, my HomeComponent view code looks like this: <div class="courses-panel"> <h3>All Courses</h3> <mat-t ...