0

I am new in angular I am trying to change the state of my button in the navbar, taking into consideration the navigation route, however when clicking my button I select all the other buttons including the button pressed.

Here I have my method which I call on the button:

private status = false;
selectOnMenu(event) {
    const urlBase = this.location.path();
    if (urlBase === '/documents/index/my') {
        this.status = !this.status;
    } else if (urlBase === '/documents/index/sending') {
      this.status = !this.status;
    } else if (urlBase === '/documents/index/receiving') {
      this.status = !this.status;
    } else if (urlBase === '/documents/index/received') {
      this.status = !this.status;
    } else if (urlBase === '/documents/index/finished') {
      this.status = !this.status;
    } else {
      this.status = status;
    }
  }

and this is the menu of my buttons:

<div class="btn-group" role="group" aria-label="...">
            <a class=" btn btn-square" (click)="selectOnMenu($event)" [ngClass]="status ? 'active' : ''"  routerLink="/documents/index/my">MIS DOCUMENTOS</a>
            <a  class=" btn btn-square" (click)="selectOnMenu($event)" [ngClass]="status ? 'active' : ''" routerLink="/documents/index/sending">PENDIENTES POR DESPACHAR</a>
            <a class=" btn btn-square" (click)="selectOnMenu($event)" [ngClass]="status ? 'active' : ''" routerLink="/documents/index/receiving">PENDIENTES POR RECEPCIONAR</a>
            <a class=" btn btn-square" (click)="selectOnMenu($event)" [ngClass]="status ? 'active' : ''" routerLink="/documents/index/received">RECEPCIONADOS</a>
            <a class=" btn btn-square" (click)="selectOnMenu($event)" [ngClass]="status ? 'active' : ''" routerLink="/documents/index/finished">FINALIZADOS</a>
          </div>

I have tried to change my method but it still marks all the buttons when I click, which is incorrect, since only the selected button should be highlighted.

enter image description here

Erick91
  • 57
  • 1
  • 9

3 Answers3

1

Your error is using same variable (status) for all buttons. And ofcourse ngClass will behave same for all. If you want to use ngClass you must use seperate variables for each control or for this feature use routerLinkActive="active" property.

AbdurrahmanY
  • 809
  • 13
  • 22
0

You are doing too much as a new bee.

use routerLinkActive, once that route will be active that active class will automatically be selected, explore the link

for example:

<a class=" btn btn-square" 
 routerLinkActive="active"  
 routerLink="/documents/index/my">MIS DOCUMENTOS</a>
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85
0

You can look at RouterLinkActive in Angular which will do the job.

<a routerLink="/documents/index/sending" routerLinkActive="active">Bob</a>

And you won't even need the call to the selectOnMenu()

Yin
  • 437
  • 1
  • 6
  • 15