Reputation: 47
I'm working on an ionic project & in my project when I click on 1 button other button also changes their values as they have same event in it. But I want opposite of that, clicking on a button should only change a particular button's value.
HTML<table class="student_list">
<tr><ion-item *ngFor="let record of data">
<ion-avatar slot="start">
<img src="assets/student.png">
</ion-avatar>
<ion-label class="text2">{{record.name}} {{record.id}}
<span class="button1"><button (click)="toggleBackgroundColor()" ion-button [style.background-color]="hexColor" class="btn">{{text}}</button></span>
</ion-label>
</ion-item></tr>
</table>
TS file
public toggleBackgroundColor(): void {
if(this.hexColor === '#1e90ff') {
this.hexColor = '#ff0000'
this.text='A';
} else {
this.hexColor = '#1e90ff';
this.text = 'P'
} }
Upvotes: 1
Views: 531
Reputation: 1481
I think your other buttons use the same hexColor
variable. So, when you modify your hexColor
, it updates every buttons' attribute bound on hexColor
.
I suggest you to refactor your code to modify the DOM directly.
<button (click)="toggleBackgroundColor($event)"
ion-button
[style.background-color]="hexColor"
class="btn">{{text}}
</button>
public toggleBackgroundColor(event): void {
let btnColor = event.srcElement.style['background-color'];
if (btnColor === '#1e90ff') {
btnColor = '#ff0000';
event.srcElement.innerHTML= 'A';
} else {
btnColor = '#1e90ff';
event.srcElement.innerHTML = 'P';
}
}
Upvotes: 0
Reputation: 1956
You might use a parameter which will differentiate buttons one from other. For example,
(click)="toggleBackgroundColor(1)"
will be used for one button and
(click)="toggleBackgroundColor(2)"
will be used for the other. And function then become:
public toggleBackgroundColor(who: number): void {
switch(who) {
case 1: /// I'm one button
break;
case 2: /// I'm another :)
break;
}
}
Upvotes: 1
Reputation: 448
You should put an identifier on the function call to the particular tag you are invoking the call to.
<button id="changeable" (click)="toggleBackgroundColor('changeable')" ion-button [style.background-color]="hexColor" class="btn">{{text}}</button>
And the function:
public toggleBackgroundColor(id): void {
var element = document.getElementById(id);
if(element.hexColor === '#1e90ff') {
element.hexColor = '#ff0000'
element.text='A';
} else {
element.hexColor = '#1e90ff';
element.text = 'P'
} }
Upvotes: 1
Reputation: 32535
You most probably use the same bindings for both buttons. You will have to use 2 sets of separate bindings - one for each button.
Upvotes: 1