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

Opening the Gmail app from a link using JavaScript

What is the best way to open the Gmail app from a hyperlink? This link opens WhatsApp <a href="https://wa.me/">whatsapp</a> <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1f190f ...

Retrieving information from an http request within a for loop in an Angular 2+ application

I have a scenario where I need to call my http request inside a for loop in order to process 1000 items at a time. Here's the code snippet that implements this logic: getData(IDs: string[]): Observable<any> { // IDs is a large array of strin ...

Exploring the world of JavaScript by dynamically retrieving all class functions

Is there a way to retrieve an array of all functions from a given class, including functions inherited from parent classes? For instance: class Foo extends Bar { funcA() {} } class Bar { funcB() {} } const instanceFoo = new Foo(); getClass ...

Head styles for tinyMCE

When viewing the tinyMCE example on the official website using Firefox, you may notice the editor blinking. This issue seems to only occur in Firefox, possibly due to external CSS files for the editor. I am considering adding all CSS rules directly into th ...

The content at “http://localhost:3000/script.js” could not be accessed because of a MIME type mismatch with the X-Content-Type-Options set to nosniff

I encountered an issue while attempting to transfer all the JavaScript to a separate js file and then adding that js file to the html per usual. The console displayed the following error message: The resource from “http://localhost:3000/public/main.js” ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...

What is the best way to define a variable in EJS?

I need to populate my database array results on the frontend using EJS. The code snippet I'm using is as follows: var tags = ["<%tags%>"] <% for(var i=0; i<tags.length; i++) { %> <a href='<%= tags[i] %&g ...

Transmit a PDF byte array from JavaScript to PHP using Ajax, then utilize the PHP file to send an email

I am facing a particular issue. Currently, I am utilizing the pdf-lib library for JavaScript to generate a PDF. The last step involves creating a uint8array: const pdfBytes = await pdfDoc.save() My goal is to transmit these pdfbytes via AJAX to a PHP fi ...

Steps for Disabling Autocomplete in a JSP Page

How can I prevent the browser from remembering the username and password on my JSP page after submitting the form? I've already tried using autocomplete=off in the JSP code. <form name="indexFrm" id="indexFrm" autocomplete="off" method="post"> ...

I'm looking for a way to retrieve an object from a select element using AngularJS. Can

I am working with a select HTML element that looks like this: <select required="" ng-model="studentGroup"> <option value="" selected="">--select group--</option> <option value="1">java 15-1</option> <option value="2">ja ...

Angular's custom validator consistently returns a null value

I need help with validating the uniqueness of a username field in a form where an administrator can create a new user. I have implemented a uniqueUserNameValidator function for this purpose, but it always returns null. I suspect that the issue lies in the ...

Vuetify: Utilizing condition-based breakpoints

Here is the layout that I am working with: https://i.stack.imgur.com/qlm60.png This is the code snippet that I have implemented: <template> <v-card> <v-card-text> <v-container grid-list-xl fluid class="py-0 m ...

Extracting specific keys from JSON data

I am working with an array named cols: var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic The JSON data is coming from the backend as: info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84} If I want to sel ...

Having trouble reading JSON file with Angular 4's async pipe?

Currently, I am in the process of working on a demo for Async pipe. One of the methods called is supposed to retrieve data from a JSON file containing information about books. Unfortunately, I am encountering a 404 error when attempting to access the JSON ...

What steps are needed to configure ESLint to exclusively analyze .ts files?

I need ESLint to exclusively focus on processing .ts files and not .js files. In order to achieve that, I made a .eslintignore file and included the following lines: *.js **/*.js Nevertheless, it appears that ESLint is disregarding this file. Is there so ...

Unable to invoke an external function from bolt Response Handler Callback

I am facing an issue where I am unable to call my Update method from the bolt responseHandler. Can someone please help me with this problem? Using Angular 9: Error: core.js:1673 ERROR TypeError: this.updatePaymentInfo is not a function at Object.resp ...

Retrieving the output from a nested function within a function in a Node.js application connected to a

I'm currently working on a basic web application that interacts with a database by performing INSERT and SELECT operations on a single table. While I have utilized a function from various tutorials, I am struggling to retrieve the results from the SEL ...

Implementing JSON responses in Express JS

My apologies for any language errors as English is not my first language, I am using Google Translate :) I have a question.. Here is the MySQL Query I am working with: SELECT destinations.*, questions.*, answers.* FROM destinations INNER JOIN questions ...

Exploring GatsbyJs: Optimal Strategies for Storing Strings and Text on Static Websites

Currently in the process of building a website using Gatsby JS and Material UI. I'm wondering about the best approach for storing the site content. This website will serve as a promotional platform for a small business. Should I store the text direct ...

The Windows platform is not recognizing the --port option when using ng serve

When running ng serve in Windows, it doesn't recognize the --port option. However, I found that it works if I use npm run ng serve --port portnumber and it always defaults to 4200: oml005@W7-2UA532159M MINGW64 /d/COT-TF/cot-web/cot-web (master) ng ...