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:
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With