In Angular application, the main App component remains as it is even after a user navigates from one page to other. Sometimes, you may need to show different styles when a user visits other route or page like changing the background color.
Here you will learn how we can change the background color using the Router class and using its NavigationEnd event handler in a subscription.
How to Change Background color or any style in Angular components?
Step 1) Import Router and NavigationEnd class into the App component
import { NavigationEnd, Router } from '@angular/router';
Step 2) Inject the Router
class into the contractor of class
constructor(private router: Router) {}
Step 3) Now add the Router
subscription with the NavigationEnd
event
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
...
}
});
Step 4) Use the router.url
to create a custom Class selector
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.activePath = event.url.split('/')[1] || 'default';
this.activeClassName = this.activePath + 'PageClass';
console.log(this.activeClassName);
}
});
The App Component class will look like this:
import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
activePath: string = '';
activeClassName: string = '';
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.activePath = event.url.split('/')[1] || 'default';
this.activeClassName = this.activePath + 'PageClass';
console.log(this.activeClassName);
}
});
}
}
Here we have created a custom class and assigned it to the activeClassName
variable. This variable we will add into the wrapper of the AppComponent HTML template as shown below:
<div class="{{activeClassName}}">
<a routerLink="/dashboard">Dashboard</a> |
<a routerLink="/profile">Profile</a> |
<a routerLink="/settings">Settings</a><br><br>
Active Path : <b>{{activePath}}</b>
<router-outlet></router-outlet>
</div>
Finally, add the custom style classes for each path into the app.component.css/scss file:
.dashboardPageClass {
background-color: aqua;
font-style: italic;
}
.profilePageClass {
background-color: red;
font-family: 'Courier New', Courier, monospace;
}
.settingsPageClass {
background-color: yellow;
font-weight: bold;
}
Now you will see each page will have its own background color and other implemented styles:
Leave a Reply