Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Toggle active class on only button the current clicked button (not using *ngFor)

I'm trying to figure out how can I toggle the active class on only the clicked button:

This is my current code...

<div class="btn-group">
  <button class="btn btn-secondary" [ngClass]="{ 'active' : isActive }" (click)="isActive = !isActive" type="button">Premier bouton</button>
  <button class="btn btn-secondary" [ngClass]="{ 'active' : isActive }" (click)="isActive = !isActive" type="button">Second bouton</button>
  <button class="btn btn-secondary" [ngClass]="{ 'active' : isActive }" (click)="isActive = !isActive" type="button">Troisième bouton</button>
  <button class="btn btn-secondary" [ngClass]="{ 'active' : isActive }" (click)="isActive = !isActive" type="button">Quatrième bouton</button>
</div>

...and this is the result:

enter image description here

I DO NOT USE *ngFor or ng-repeat principle. I know I need to isolate each button. How can I do that?

Adding this. to isActive doesn't work: this.isActive.

like image 254
Jonathan Avatar asked May 24 '17 17:05

Jonathan


1 Answers

Simple, just use Event Delegation.

Component.html:

<div class="btn-group" (click)="onButtonGroupClick($event)">
  <button class="btn btn-secondary" type="button">Premier bouton</button>
  <button class="btn btn-secondary" type="button">Second bouton</button>
  <button class="btn btn-secondary" type="button">Troisième bouton</button>
  <button class="btn btn-secondary" type="button">Quatrième bouton</button>
</div>

Component.ts/.js:

  onButtonGroupClick($event){
    let clickedElement = $event.target || $event.srcElement;

    if( clickedElement.nodeName === "BUTTON" ) {

      let isCertainButtonAlreadyActive = clickedElement.parentElement.querySelector(".active");
      // if a Button already has Class: .active
      if( isCertainButtonAlreadyActive ) {
        isCertainButtonAlreadyActive.classList.remove("active");
      }

      clickedElement.className += " active";
    }

  }

Live example: https://plnkr.co/edit/EE4dOMgpY8QA2qZXjMiW?p=preview

like image 79
Marian07 Avatar answered Sep 22 '22 04:09

Marian07