My Project Journey
I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/'). The structure of my app-component includes the header and router-outlet
together like this:
<nav class="navbar navbar-default navbar-fixed-top" [hidden]="!showHeader">
<div class="container">
<div class="navbar-header>
<a class="navbar-brand" href="" [routerLink]="['/']">FARKLE! {{showHeader | json}}</a>
</div>
</div>
</nav>
<div class="container">
<router-outlet></router-outlet>
</div>
In order to update the boolean value showHeader
when the route changes, I have implemented the following logic within the component class:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
showHeader: boolean;
constructor(
private router: Router
) {}
ngOnInit () {
this.showHeader = true;
this.router.events.subscribe(this.setHeader());
}
private setHeader () {
var showHeader = this.showHeader;
return function (event) {
if (event instanceof NavigationEnd) {
showHeader = event.url === '/';
console.log(event.url, showHeader, this.showHeader);
};
};
}
}
The issue I am facing lies in updating the scope of this.showHeader
within the observable's callback function. Despite correctly setting the initial value in ngOnInit
and observing the correct behavior during navigation in the console, the value does not seem to propagate to the template. This suggests that the variable may not be accessible within the scope of the event callback.
Seeking Solutions
With this dilemma in mind, how can one effectively manipulate the component's scope within the context of an observable callback?