Skip to content Skip to sidebar Skip to footer

Change Color Of Div Based On Page Selection In Angular 4

new to Angular so please bear with me (or just point me to the appropriate docs article if this is just that obvious) Basically, the structure of my site (for all of the pages) is

Solution 1:

You could store the activateRoute as a member variable and style according to that.

exportclassAppComponent {
  activatedRoute = "";

Then, when you click on a link, you set the activatedRoute.

<a routerLink="/" routerLinkActive="active" (click)="activateRoute('home')>

activateRoute(activatedRoute: string) {
  this.activatedRoute = activatedRoute;
}

For the styling of the div, you use NgClass.

[ngClass]="{'home-class': activatedRoute === 'home', 'about-class': activatedRoute === 'about', ...}"

If you do not only want to do it, when someone clicks one of the links but always when the route is activated, then you should inject Router and check for the url.

[ngClass]="{'home-class':router.url==='/','about-class':router.url='about',...}//injecttherouterconstructor(publicrouter:Router) {}

see a running example in this plunker

Solution 2:

If you want to keep the style / conditional code out of the template in an a function, you can test the route value and return a class based on the current path. This is easy to read / maintain, although it may not be the most elegant solution:

import { Router } from '@angular/router';

constructor(
    private router: Router
) {
}

getHeaderStyle() {
    if (this.router.url.includes('/about/')
        return'red';
    } elseif (this.router.url.includes('/resources/')){
        return'green';
    } elseif (this.router.url.includes('/contact/')){
        return'yellow';
    } else {
         return'blue'
}

In your component user [ngClass] to apply the class based on the function:

<div [ngClass]="getHeaderStyle()"class="app-mainheader">
  <div class="app-mainheader__content set-margin">
  thisis the header for the
  </div>
</div>

Then create your styles for each colour:

.red {
    background-color: red;
}

etc.

Post a Comment for "Change Color Of Div Based On Page Selection In Angular 4"