Home > Mobile >  Angular btn-group Add class to button if string exists in array
Angular btn-group Add class to button if string exists in array

Time:07-06

I have a few buttons which I need to toggle an active class in each so I can change it's color when it's selected.

This is what I have:

I have this array:

this.selected  = ['one', 'two', 'three'];

The I have these buttons:

<div >
    <button (click)="checkIfInArr('one')">One</button>
    <button (click)="checkIfInArr('two')">Two</button>
    <button (click)="checkIfInArr('three')">Three</button>
</div>

And a function idea here...

checkIfInArr(name) {
    if (this.selected.includes(name)) {
        // Add .active class to button 
    } else {
        // Remove .active class from button
    }
}

This is as far as I've got.

Basically I need to toggle a class on each of the buttons.

How can I get this done either this way or another way?

CodePudding user response:

To get it done that way, obtain the button's ElementRef too from the (click) callback. Then in the function, add or remove the .active class as you need.

So your HTML will now create elementRef variables with # and pass them to the callback. So you can have this:

<div >
    <button #one (click)="checkIfInArr('one', one)">One</button>
    <button #two (click)="checkIfInArr('two', two)">Two</button>
    <button #three (click)="checkIfInArr('three', three)">Three</button>
</div>

Then the callback function will now toggle the .active class on the provided elementRef. So you can have this:

checkIfInArr(name: string, ref: ElementRef) {
    if (this.selected.includes(name)) {
        // Add .active class to button 
        ref.nativeElement.classList.add('active');
    } else {
        // Remove .active class from button
        ref.nativeElement.classList.remove('active');
    }
}
  • Related