Reputation: 349
I'm trying to hide the header, only in one route.
Let's say that I've three routes, route1
, route2
and route3
.
And I've one component called app-header
.
I want the component app-header
to be hidden when the user enters in the route1
and show this component in the other 2 routes.
I've found some topics here on stackoverflow, but none of them helped me =/
Can you guys give me some help with that?
Here's my code:
app.component.ts
export class AppComponent implements OnInit {
showHeader = true;
constructor(
private router: Router
) {
this.router.events.subscribe(event => this.modifyHeader(event));
}
ngOnInit() {
}
modifyHeader(location) { // This method is called many times
console.log(location.url); // This prints a loot of routes on console
if (location.url === '/route1') {
this.showHeader = false;
} else {
this.showHeader = true;
}
}
}
app.component.html
<app-header *ngIf="showHeader"></app-header>
<router-outlet></router-outlet>
I'm using angular 6.1.4
Upvotes: 3
Views: 4698
Reputation: 9
Using @Krishna's solution is really performance friendly as this observable can't be unsubscribed of, because it is in the root AppComponent of the app.
Upvotes: 0
Reputation: 633
Add function on router outlet
<router-outlet (activate)="modifyHeader()"></router-outlet>
In your constructor
router;
constructor(private _router: Router ) {
this.router = _router;
}
Your modifyHeader function
modifyHeader() { // This method is called many times
console.log(this.router.ur); // This prints a loot of routes on console
if (this.router.ur === '/route1') {
this.showHeader = false;
} else {
this.showHeader = true;
}
}
Let me know if you face any issue.
Upvotes: 2
Reputation: 852
Since you know which route you want to detect, and seem to have a solution in the app component in mind, I'd suggest filtering the router events, as such:
export class AppComponent implements OnInit {
showHeader = true;
constructor(
private router: Router
) {
this.router.events.pipe(
filter(e => e instanceOf NavigationEnd)
).subscribe(event => this.modifyHeader(event));
}
ngOnInit() {
}
modifyHeader(location) { // This method is called many times
console.log(location.url); // This prints a loot of routes on console
if (location.url === '/route1') {
this.showHeader = false;
} else {
this.showHeader = true;
}
}
}
Upvotes: 6