Pass data from a routed component into a child of the app component

Viewed 36

I will post some code below, however, what I am trying achieve is that on a select few pages, the background of the header will become transparent unless scrolled (however, the default should be white).

app.component.html

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

header.component.ts

import { Component, HostListener, Input } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})

export class HeaderComponent {
  @Input() scrolled: boolean = false;

  @HostListener("window:scroll", [])
  onWindowScroll() {
      this.scrolled = window.scrollY > 0;
  }
}

This seems to work, however, on say the profile page, I want to disable this functionality, how would go about settings something on the profile.component.ts (routed) to say to the header component (in app.component.ts) 'hey, don't enable the scroll functionality'?

1 Answers

So if you just want to disable some functionality on the header component for a certain route you could use the Router and listen to the route changes and do something only if it matches the route pattern or vice versa.

// app-header.component.ts
export class AppHeader implements OnInit {
  doSomethingRoutes = ['/page-a', '/page-c'];
  dontDoScrollFunctionality = false;
  constructor (private router: Router) {};

  ngOnInit() {
    this.router.events.subscribe((event) => {
        if (event instanceof NavigationEnd) {
           if (doSomethingRoutes.includes(event.url)){
               //...write your logic here?
               // something like this ....
               dontDoScrollFunctionality = false;
           } else {
              dontDoScrollFunctionality = true;
           }
        }
    })
  }
  
  @HostListener("window:scroll", [])
  onWindowScroll() {
      this.scrolled = window.scrollY > 0;
      if (!this.dontDoScrollFunctionality) {
          // ... do scroll logic
      } else {
         // whatever you want here
      }
  }

}

Im not sure if i've answered the question but i implemented a demo here, where if youre on /page-a scrolling will turn the Hello red and if youre on /page-b it will turn the Hello yellow. A caveat here is that your will prolly need to filter out the query params and other stuff from the event.url before trying to match if its the route to do the functionality.

Related