I have successfully implemented a feature where text is displayed word by word using an ngFor directive. Within the ngFor loop, there is an if-else statement that determines whether each word should be displayed as a <span>
or a <button>
.
Now, I want to modify the behavior of the buttons so that when a user clicks on a button for the first time, its background color changes to red and on subsequent clicks, it reverts back to grey.
The issue I am facing is that currently, clicking on any button changes the background color of all buttons instead of just the one clicked on. How can I modify the code to change the color of only the clicked button?
HTML:
<div id="learnerText" *ngFor="let item of wordsJsonText; let i = index" [ngClass]="{active: i === activeIndex}">
<div class="container" id="textBody" id="learnerText">
<ng-container *ngIf="item.is_title==='false' && item.has_context==='false'; then caseA else caseB">
</ng-container>
<ng-template #caseA id="textBody" id="learnerText">
<span id="learnerText">{{item.form}}</span>
</ng-template>
<ng-template #caseB>
<div *ngIf="item.is_title==='false' && item.has_context==='true'">
<Button class="btn btn-secondary" [ngStyle]="{'background-color' : toggle ? 'red' : 'grey'}"
id="bodyButton" text=item.form (click)="onClickMe(item.lemma, item.pos); toggleColor()">{{item.form}}</Button>
</div>
</ng-template>
</div>
</div>
TYPESCRIPT
private toggle: boolean;
toggleColor() {
this.toggle = !this.toggle;
}