javascript – How to change the background color of a button when I click on it?-ThrowExceptions

Exception or error:

I am starting on angular and I am developing with my internship colleagues a catalog application, here is my problem:

I have these little buttons like this in the menu:

btn menu

and I want that when I click on one of its buttons, its background will be colored in orange, like this one for example:

btn color

picture acceuil

as you can see here i clicked on the home button and it brought me back to the home page and the “home” button its background is well colored in orange.

Now I want that when I click on one of the 3 buttons that I displayed above their background is colored in orange and the other button which was selected in front of its background is colored in black, so on …

here is the code of my component.html:

<div class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
    <ul class="nav sidebar-nav">
        <li class="dropdown activ"><a class="dropdown-toggle" [routerLink]="['home']" class="active" data-toggle="dropdown"><i class="fa fa-fw fa-home"></i> Accueil </a></li>
        <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-search"></i> recherche <span class="caret"></span></a>
        <ul class="dropdown-menu" role="menu">
            <li class="element"><a [routerLink]="['nonRelationEntity']"><i class="fa fa-fw fa-angle-right "></i> entités sans relations</a></li>
        </ul></li>
        <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-book"></i> catalogue <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li class="element"><a [routerLink]="['entity']"><i class="fa fa-fw fa-angle-right "></i> entité</a></li>
                <li class="element"><a [routerLink]="['relation']"><i class="fa fa-fw fa-angle-right "></i> relation</a></li>
                <li class="element"><a [routerLink]="['gestionCatalogue']"><i class="fa fa-fw fa-angle-right "></i> gestion catalogue</a></li>
            </ul></li>
        <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-exchange-alt"></i> mapping <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li class="element"><a [routerLink]="['profileMapping']"><i class="fa fa-fw fa-angle-right "></i> mapping des profiles</a></li>
                <li class="element"><a [routerLink]="['profile']"><i class="fa fa-fw fa-angle-right "></i> profile</a></li>
                <li class="element"><a [routerLink]="['scopeMapping']"><i class="fa fa-fw fa-angle-right "></i> mapping des scopes</a></li>
                <li class="element"><a [routerLink]="['scope']"><i class="fa fa-fw fa-angle-right "></i> scope</a></li>
            </ul></li>
        <li *ngIf="edit" class="element"><a [routerLink]="['import']"><i class="fa fa-fw fa-arrow-alt-circle-up  "></i> import</a></li>
        <li class="element"><a [routerLink]="['export']"><i class="fa fa-fw fa-arrow-alt-circle-down  "></i> export</a></li>
        <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-cogs"></i> administration <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li class="element"><a [routerLink]="['catalog']"><i class="fa fa-fw fa-angle-right "></i> catalogue</a></li>
                <li class="element"><a [routerLink]="['mappingType']"><i class="fa fa-fw fa-angle-right "></i> type de mapping</a></li>
                <li class="element"><a [routerLink]="['mappingSystem']"><i class="fa fa-fw fa-angle-right "></i> système de mapping</a></li>
                <li class="element"><a [routerLink]="['entityType']"><i class="fa fa-fw fa-angle-right "></i> type d'entité</a></li>
                <li class="element"><a [routerLink]="['relationType']"><i class="fa fa-fw fa-angle-right "></i> type de relation</a></li>
                <li class="element"><a [routerLink]="['propertyType']"><i class="fa fa-fw fa-angle-right "></i> propriété</a></li>
                <li class="element"><a [routerLink]="['mappingContext']"><i class="fa fa-fw fa-angle-right "></i> contextes de mapping</a></li>         
                <li *ngIf="admin" class="element"><a [routerLink]="['users']"><i class="fa fa-fw fa-angle-right "></i> gestion des utilisateurs</a></li>
                <li class="element"><a [routerLink]="['version']"><i class="fa fa-fw fa-angle-right "></i> gestion de versions</a></li> 
            </ul>
        </li>
    </ul>
</div>

and here is the code for my component.ts:

import { Component } from '@angular/core';
import { RouterModule, Router, Routes } from '@angular/router';
declare var $: any;

@Component({
    selector: 'side-menu',
    templateUrl: './side-menu.component.html',
    styleUrls: ['./side-menu.component.css']
})
export class sideMenuComponent {
    admin : boolean = false;
    edit : boolean = true;
    ngOnInit(){
        if(localStorage.getItem('role')=="ROLE_ADMIN"){
            this.admin = true;
        }
        if(localStorage.getItem('role')=="ROLE_VIEW"){
            this.edit = false;
        }
    }

    ngAfterViewInit() {
        $(document).on('click', '.element', function (e) {
            $('.element.activ').toggleClass('activ');
            $(this).toggleClass('activ');
        });

        $(document).on('click', '.sidebar-nav li a', function (e) {
            $('.element.activ').toggleClass('activ');
        });

        $(document).on('click', ':not(.sidebar-nav li.open a)', function (e) {
            e.stopPropagation();
        });
/* remove if classe is active */
        $('.nav a').on('click', function () {
            $('.nav').find('.activ').removeClass('activ');
        });
    }
}

and here is my css code:

  /*.woll {
    margin-bottom: -21px;
}

.ssilka a{
    color:#0080C0;
}

.ssilka a:hover{
    color:#0080C0;
}

.list-group-item:last-child {
    border-radius: 0;
}

.list-group-item:first-child{
    border-radius: 0;
}
.side-menu{
    width: 20%;
}*/
#sidebar-wrapper { 
  -moz-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  -webkit-transition: all 0.25s ease;
  background: #222;
  height: 100%;
  width: 180pt;
  left: 180pt;
  margin-left: -180pt;
  -webkit-transition: all 0.25s ease;
  transition: all 0.25s ease;
  z-index:-5;
}
#sidebar-wrapper::-webkit-scrollbar {
  display: none;
}
#sidebar-wrapper.toggled{
    left:0;
}

.nav .open > a { background-color: transparent; }

.nav .open > a:hover { background-color: transparent; }

.nav .open > a:focus { background-color: transparent; }

.sidebar-nav {
  list-style: none;
  margin: 0;
  padding: 0;
  position: absolute;
  top: 70pt;
  width: 180pt;
}

.sidebar-nav li {
  display: inline-block;
  line-height: 14pt;
  position: relative;
  width: 100%;
}

.sidebar-nav li:before {
  -moz-transition: width 0.2s ease-in;
  -ms-transition: width 0.2s ease-in;
  -webkit-transition: width 0.2s ease-in;
  background-color: #1c1c1c;
  content: '';
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  -webkit-transition: width 0.2s ease-in;
  transition: width 0.2s ease-in;
  width: 3pt;
  z-index: -1;
}

/*.sidebar-nav li:first-child a {
  background-color: #222;
  color: #ffffff;
}*/

.sidebar-nav li:nth-child(1):before, .sidebar-nav li:nth-child(1).open, .sidebar-nav li:nth-child(1).activ { background-color: #F55000; }

.sidebar-nav li:nth-child(2):before, .sidebar-nav li:nth-child(2).open, .sidebar-nav li:nth-child(2).activ { background-color: #F6590D; }

.sidebar-nav li:nth-child(3):before, .sidebar-nav li:nth-child(3).open, .sidebar-nav li:nth-child(3).activ  { background-color: #F7621A; }

.sidebar-nav li:nth-child(4):before, .sidebar-nav li:nth-child(4).open, .sidebar-nav li:nth-child(4).activ  { background-color: #F86B27; }

.sidebar-nav li:nth-child(5):before, .sidebar-nav li:nth-child(5).open, .sidebar-nav li:nth-child(5).activ  { background-color: #F97435; }

.sidebar-nav li:nth-child(6):before, .sidebar-nav li:nth-child(6).open, .sidebar-nav li:nth-child(6).activ  { background-color: #FA7D42; }

.sidebar-nav li:nth-child(7):before, .sidebar-nav li:nth-child(7).open, .sidebar-nav li:nth-child(7).activ  { background-color: #FB864F; }

.sidebar-nav li:nth-child(8):before, .sidebar-nav li:nth-child(8).open, .sidebar-nav li:nth-child(8).activ  { background-color: #FC8F5D; }

.sidebar-nav li:nth-child(9):before, .sidebar-nav li:nth-child(9).open, .sidebar-nav li:nth-child(9).activ  { background-color: #FD986A; }

.sidebar-nav li:nth-child(10):before, .sidebar-nav li:nth-child(10).open, .sidebar-nav li:nth-child(10).activ  { background-color: #FEA177; }

.sidebar-nav li:nth-child(11):before, .sidebar-nav li:nth-child(11).open, .sidebar-nav li:nth-child(11).activ  { background-color: #FFAB85; }

.sidebar-nav li:hover:before {
  -webkit-transition: width 0.2s ease-in;
  transition: width 0.2s ease-in;
  width: 100%;
}

.sidebar-nav li a {
  color: #dddddd;
  display: block;
  padding: 7pt 10pt 7pt 20pt;
  text-decoration: none;
}

.sidebar-nav li.open:hover before {
  -webkit-transition: width 0.2s ease-in;
  transition: width 0.2s ease-in;
  width: 100%;
}

.sidebar-nav .dropdown-menu {
  background-color: #333;
  border-radius: 0;
  border: none;
  box-shadow: none;
  margin: 0;
  padding: 0;
  position: relative;
  width: 100%;
}

.sidebar-nav .dropdown-menu li a{
  margin-left: 10pt;
}

.sidebar-nav li.open a, .sidebar-nav li a:hover, .sidebar-nav li a:active, .sidebar-nav li a:focus, .sidebar-nav li.open a:hover, .sidebar-nav li.open a:active, .sidebar-nav li.open a:focus {
  background-color: transparent;
  color: #ffffff;
  text-decoration: none;
}

.sidebar-nav > .sidebar-brand {
  font-size: 14pt;
  height: 52pt;
  line-height: 30pt;
}

.caret{
    float: right;
}

The problem is that this code does not work on the import and export button and I really do not know where it is the error!

I look forward to your response! your help would be really useful, and sorry if my question is stupid but I’m still just a beginner on this framework.

And thank you in advance for your response!

How to solve:

In Angular, there are sooo many ways to do this. Basically, it’s just state control.

For this example, I’m using a property in the class, but you could also use a property on an object or any other thing (like returning a class from a function).

Don’t Use JQuery

JQuery was great, but in Angular, just don’t do it. Angular provides better ways to update the DOM without re-writing everything Angular does OoTB.

You can see the example in Action here

But the important parts:

<button type="button" [ngClass]="{'blue-button' : isBlue }" (click)='toggleButtonClass()'>Click Me</button>

A Button with a click event, and a class based on the state of a boolean value.

A little CSS for the button:

.blue-button {
 background-color:blue;
 color:white;
 }

And finally the function for toggling the class:

public toggleButtonClass(){
   this.isBlue = !this.isBlue;
}

Additionally, you could have an array of “Button” objects like:

export class Button implements IButton {
Text: string;
Value: string;
IsSelected?: boolean = false;
}

And then generate controls that do the same thing:

<div *ngFor="let button of Buttons">
   <button type="button" 
      (click)="toggleSelectedButton(button)" 
      [ngClass]="{'blue-button' : button.IsSelected}">{{button.Text}}
   </button>
</div>

###

I recommend you use HostListener and HostBinding, so you create a directive that changes the color on click for example, and then you reuse it anywhere you want.

Please take a look at this example

  @Directive({
  selector: `[appHighlight]`
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer) { }

  @HostListener('document:click', ['$event'])
  handleClick(event: Event) {
    if (this.el.nativeElement.contains(event.target)) {
      this.highlight('yellow');
    } else {
      this.highlight(null);
    }
  }

  highlight(color) {
    this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
  }
}

and then in html

<div>
  <p appHighlight>
    <span>Text to be highlighted</span>
  </p>
</div>

you can find a working example on this page.

Leave a Reply

Your email address will not be published. Required fields are marked *