Search code examples
javascriptangulartypescriptng-style

How to change the background color when I click a <li> in Angular?


I have a kind of side bar menu. Like this:

 Projects: 
       All
       project1
       project2

When I click an item I want to changed it the background-color. (from black to green).

Projects: 
           All
           project1 // This was clicked and I want to be GREEN
           project2

But, what I did until now was to changed the color for all of the projects when I clicked a project. All of them are green know. I don't know how to do that for a particular item.

<div class="container">
  <h5>Projects: </h5>
  <div class="container-fluid">
    <ul class="nav navbar-nav side-nav">
      <li routerLinkActive="active" class="nav-item">
        <a (click)="activeProject()" [ngStyle]="{'background-color':isActiveProject? 'green' : 'white' }" routerLink="/tasks" href="#">All</a>
      </li>
    </ul>
    <ul class="nav navbar-nav side-nav" *ngFor="let project of projects">
      <li routerLinkActive="active" class="nav-item" >
        <a (click)="activeProject()" [ngStyle]="{'background-color':isActiveProject? 'green' : 'white' }" [routerLink]="['/tasks/project/', project.projectId]" href="#">{{project.projectName}}</a>
      </li>
    </ul>
  </div>
</div>

In the component:

isActiveProject: boolean;

activeProject() {
    this.isActiveProject = true;
  }

I suppose that this active project method is apply for all the li elements, an remains active when it was stetted on true.


Solution

  • I see you have a routerLinkActive="active", this should set the active class on the li element. Then in your CSS, you can do:

    li.nav-item.active { background: green; }
    

    You may have to set [routerLinkActiveOptions]="{exact: true}" for exact routing and highlighting.

    Then you can get rid of isActiveProject for the change of background color and the ngStyle.