Home > front end >  How can i push the Title of Page to Index on reload
How can i push the Title of Page to Index on reload

Time:04-18

I have a app which uses a a menu bar to enable the user to call certain functions as well as display the page / component he is in which looks something like the below.

enter image description here

The way I currently set the title is via the route

this.selectedDisplayName = this.router.routerState.snapshot.root.data['displayName'];

{
        path: 'MassEmail',
        component: MassEmailComponent,
        data: {displayName: 'Mass Email'},
},

This works fine as long as the user uses the menu to get to the component. The issue I have is that if a user clicks the refresh button on its browser the title wont come back as the the user reaches the component with out calling a route. Is there a way to push on a reload the Title to the Index Page ?

CodePudding user response:

You could use a service that holds the state of the page, one of the properties of that state could be the current page title, which you set in the component constructor. Other properties could be active tabs/options on hidden pages during the current session, etc... For this use a subject to which you can subscribe, so that when the page switches, your HTML (using the async pipe) automatically updates

In the service, you'd have something like

import { Injectable } from '@angular/core';
import { throwError, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class StateService {
  private currentPagetitle: Subject<string> = new Subject<string>();

  getTitle(): Observable<string> {
    return this.currentPagetitle;
  }
  setTitle(title: string): void {
    this.currentPagetitle.next(title);
  }
}

And then in the component which holds the title bar (my example this was app.component)

  name: Observable<string>;

  constructor(private state: StateService) {
    this.name = state.getTitle();
  }

note the HTML in the header, which in my stackblitz is located in the app component.html:

<h1>Name: "{{ name | async }}"</h1>

check out this stackblitz minimal example

I've added a way to prevent your service from bloating by using a generic class, and mentioned my first thoughts as pro/con to that approach.

  • Related