pitinca
pitinca

Reputation: 143

change header background based on navigation

My project structure is the following:

app
-----pages-parts |
                 |header
                 |footer

-----pages       |
                 |homepage
                 |contacts
                 |...etc...

-----airports    |
                 |airport-template
                 |airport-1
                 |airport-2
                 |...etc...

In my app.component.html I have:

<app-header></app-header>
<router-outlet></router-outlet> //<- here I load homepage for first instance
<app-footer></app-footer>

So, I load header component in all pages.

Then, for example, in the airports section I load airport-template component and I put the contents (texts and other stuffs) stored in airport-1 component by using @Input.

In the same way, I need to change the header background based on airport-1, airport-2 navigation but I'm still not able to figure it out.

I tried @Input again but with no success. I also tried to apply different styles on the same header class in airport-1.component.scss with no success (I think it is due to View Encapsulation).

Is there a way to solve my problem?

Any suggestions will be appreciated.

Upvotes: 0

Views: 475

Answers (2)

Andrei
Andrei

Reputation: 12196

There are some ways to do that: 1: place styles inside of a parent and prepend child selector with /ng-deep/ thus styles won't be 'incapsulated' into parent and will affect child. 2: subscribe to router.events.subscribe(event => analyze(router.url)) and handle url of the router 3: Witch I like the most will leave logic in parent component, but styles in header.scss

<app-header [ngClass]="{'blue-background': shouldBeBlue}"/>

<!-- header.scss -->
:host.blue-background {
  .some-element {
    background: blue;  
  }
}

Upvotes: 0

Charly Sosa
Charly Sosa

Reputation: 575

In header component inside ngOnInit method you must subscribe to each route's change.

import { NavigationEnd, Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
…
subscriptionRoute: Subscription;
classBackground: string = '';
…
constructor(
  private router: Router
) {}
ngOnInit() {
  this.subscriptionRoute = this.router.events.subscribe((event) => {
    if (event instanceof NavigationEnd) {
      console.log(event.url);
      //here set classBackground property
    }
  });
}

In header html use ngClass to assign classBackground

Regards

Upvotes: 1

Related Questions