0

I have two URLs on my site

  1. https://example.com -> Main page
  2. https://example.com/test -> Inner Page

Header and Footer are different for both URLs.

On the inner page, I add the link to go main page (https://example.com) for this I used the routerLink="/" the contents are loaded correctly but the header and footer contents are not updated to the main page still keep the inner page.

My Analysation is Header component ngInit is not triggered. Sample codes I have added the RouterModule in SharedModule.ts

app.component.ts

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

header.component.ts

this.router.events.pipe(takeUntil(this.onDestroy$)).subscribe((events) => {
      if (events instanceof NavigationEnd) {
        if () {
          //main page logic
        } else {
          //inner page logic
      }
    });

Some reference threads are: https://stackoverflow.com/a/45865355/8119756

Thanks in advance.

Poonkodi
  • 99
  • 1
  • 7

1 Answers1

0

Create a CommonService and use Rxjs Behaviour subject and inject this common service in header and footer and in all components from where you wanted to update headers and footers.

CommonService.ts

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
private headerDataUpdateSource = new  new BehaviorSubject<any>("");
onHeaderDataUpdate = this.headerDataUpdateSource.asObservable();

 updateHeaderData(message: any) {
    this.headerDataUpdateSource.next(message);
  }

in appheader.component.ts, listen for the event

constructor(private commonService: CommonService){
 this.commonService.onHeaderDataUpdate.subscribe((data: any) => {
 this.headerText= data;
 })
}

// from any other component, lets say profile.component.ts, invoke this commonservice method with data

profile.component.ts

updateHeader(){
 this.commonService.updateHeaderData("New User");
}

similarly, create another BehaviourSubject for footer.

AhammadaliPK
  • 3,448
  • 4
  • 21
  • 39
  • 1
    I used the common service for the open/close sidebar. I will try the same for updating header content. Thank you. – Poonkodi Aug 21 '21 at 16:30