Home > Enterprise >  class.active is not changing through (click) event handler
class.active is not changing through (click) event handler

Time:06-04

I'm trying to create a kind of toggle action when two buttons in angular.

Buttons to code

So, what should happen is when I click trending, burst should appear as inactive and vice versa. I'm trying to do this through [class.active] on angular:

<div >
        <button [class.active]="burstButton" (click)="onTabChange()" clickable>Burst</button>
    </div>
    <div >
        <button [class.active]="trendingButton"  (click)="onTabChange()" clickable>Trending</button>
    </div>

I tried to do this by declaring two boolean variables, one for each button:

public trendingButton: boolean = true;
public burstButton: boolean = false;

And handle the click event through a function obviously:

onTabChange() {

    console.log('Hello from ontabchange')
    if (this.trendingButton) {
      this.burstButton = false;
    } else {
      this.burstButton = true;
    }

}

My problem is, no matter what button I click, nothing happens. The log print on onTabChange appears in the console when I click either button so I don't understand what's going on.

Thank you in advance

CodePudding user response:

The logic in your onTabChange seems wrong. The value of this.trendingButton will always be true, and thus this.burstButton will always be assigned the false value from the first branch of your if-else.

Most importantly, have you defined the .active class in your CSS file? If not, then what you see is the expected behavior.

CodePudding user response:

You have wrong logic in onTabChange and one extra variable. Make html code execute onTabChange with name of button:

<div >
        <button [class.active]="currentButton === 'burst'" (click)="onTabChange('burst')" clickable>Burst</button>
    </div>
    <div >
        <button [class.active]="currentButton === 'trending'"  (click)="onTabChange('trending')" clickable>Trending</button>
    </div>

int TS file:

public current: string = 'burst';
onTabChange(buttonName: string) {

    console.log('Hello from ontabchange')
    this.currentButton = buttonName;

}

Hope this helps.

  • Related