4

I have:

<button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked"

Result:

10x button on screen.

When I click on the button number 1: Each button will get class ".active"

But I would like:

When I click button number 1: will get class ".active".

When I click button number 3: will get class ".active".

When I click button number 6: will get class ".active".

Result:

Button 1, Button 3, Button 6 - Each this buttons will get class ".active"

How to do that?

PLUNKER: https://plnkr.co/edit/lX3DjN46STmo6gfBkPCc?p=preview

2

2 Answers 2

8

Just maintain a temporary array

<button *ngFor="let button of [1,2,3,4]; let i = index" [ngClass]="{'active':isClicked[i]}" (click)="isClicked[i] = (isClicked[i]? false :true )">button</button>

in component public isClicked = [];

working fiddler --> https://plnkr.co/edit/MwuWhtBPPQUQCG2Y9qmx?p=preview

Hope it helps!!

Sign up to request clarification or add additional context in comments.

Comments

3

When you use (click)="isClicked = !isClicked", you set a single isClicked property on the component that is used by all buttons. Instead, expand your buttons array to an array of objects:

buttons = [
    { text: 'item1', isClicked: false },
    { text: 'item2', isClicked: false },
    { text: 'item3', isClicked: false },
    // ...
]

With this, each button has its own isClicked property, which you can use like this:

<button *ngFor="let button of buttons" [ngClass]="{'active': button.isClicked}" (click)="button.isClicked = !button.isClicked">
    {{ button.text }}
</button>

Here's an updated plunker.

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.