Karan
Karan

Reputation: 1118

Data Sharing between Angular components

I am new in angular 6. I am creating a project using angular 6. I am coming in to a problem while sharing the data. Here is the project structure:

1) Header Component 2 Login Component 3) Home Component 4) Shared Service

I am adding the class in my header component on the basis of current route. This was working on page refresh. But when i move from one component to other this was not working.

Here is the code:

Layout Component is:

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

Header Component:

 ngOnInit() {
    console.log(this.dataService.urlExists())
    if(this.dataService.urlExists()){
      this.url = true
     }else{
       this.url = false
     };

  }
<header class="stick-top forsticky" id="header" [ngClass]="{'gradient': url==true}">
</header>

Shared Service:

urlExists(){
     this.url = this.router.url
     if(this.url == "/"){
         return false;
     }else{
         return true;
     }
 }

Please note: On page refresh this is working..

Upvotes: 1

Views: 102

Answers (1)

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

It is because, your header component is not reinited when navigating as it is outside of router-outlet. You need to listen route changes and perform desired operations accordingly.

So in the Header Component, you can subscribe to router events and listen NavigationEnd events to check URL:

import {NavigationEnd, Router} from '@angular/router';
import {filter} from 'rxjs/operators';
...



constructor(private router: Router) {
    this.subscribeRouterEvents();

}

subscribeRouterEvents = () => {
    this.router.events.pipe(
      filter(e => e instanceof NavigationEnd)
    ).subscribe(() => {
       console.log(this.dataService.urlExists())
       if(this.dataService.urlExists()){
          this.url = true
       }else{
          this.url = false
       };
    });

Upvotes: 3

Related Questions