Adding the active class to each clicked button, Angular 4

后端 未结 2 950
名媛妹妹
名媛妹妹 2021-01-13 14:53

I have:

相关标签:
2条回答
  • 2021-01-13 15:13

    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!!

    0 讨论(0)
  • 2021-01-13 15:18

    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.

    0 讨论(0)
提交回复
热议问题