0

Hello I need to create toggle buttons, but when I click first button active class works for both element.

HTML

 <button [class.active]="k" (click)="toggle()">1</button>
 <button [class.active]="k" (click)="toggle()">2</button>

TS

k: boolean = false;
toggle(): void {
   this.k = !this.k;
}
0

3 Answers 3

2
 <button (click)="toggle($event)">1</button>
 <button (click)="toggle($event)">2</button>

TS:

toggle(event): void {
    event.target.classList.toggle("active");
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to either use two different variables or an array to bind to.

With separate variables

<button [class.active]="k1" (click)="k1 = !k1">1</button>
<button [class.active]="k2" (click)="k2 = !k2">2</button>
k1: boolean = false;
k2: boolean = false;

With array

<button [class.active]="k[0]" (click)="toggle(0)">1</button>
<button [class.active]="k[1]" (click)="toggle(1)">2</button>
k: boolean[] = [];
toggle(index: number): void {
    this.k[index] = !this.k[index];
}

Comments

1

Use a unique string for separate buttons

<button [class.active]="button1" (click)="toggle("button1")">1</button>
<button [class.active]="button2" (click)="toggle("button2")">2</button>

And your function can be modified as

toggle(button): void {
   this.button = !this.button;
}

Note: I'm just providing you a idea that you should pass different values for separate buttons.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.