M. Fonteles
M. Fonteles

Reputation: 21

Changing specific button color onclick in Ionic 2

This is my html sample:

<ion-col col-6>
    <button ion-button block (click)="toggleNamedColor()" ion-button [color]="ionicNamedColor">
      test
    </button>
  </ion-col>
  <ion-col col-6>
    <button ion-button block ion-button block (click)="toggleNamedColor()" ion-button [color]="ionicNamedColor">
      test
    </button>
  </ion-col>

I have here a list of about 12 buttons that i want to have their color be individually changed when they are clicked, all sharing the same method. Here is the typescript:

export class PopoverComponent {


public ionicNamedColor: string = 'primary';

constructor() {
}

public toggleNamedColor(): void {
  if (this.ionicNamedColor === 'primary') {
    this.ionicNamedColor = 'light'
  } else {
    this.ionicNamedColor = 'primary'
  }
}

The problem: Right now this code makes all buttons change color when any of them is clicked. How can i change this so only that specific button is changed, and not change the variable for all others?

Upvotes: 0

Views: 5556

Answers (1)

Nima Hakimi
Nima Hakimi

Reputation: 1392

try sending $event to your toggle function

<ion-col col-6>
    <button ion-button block (click)="toggleNamedColor($event)" ion-button color="primary">
      test
    </button>
</ion-col>

<ion-col col-6>
    <button ion-button block ion-button block (click)="toggleNamedColor($event)" ion-button color="primary">
      test
    </button>
</ion-col>

and then in your function you need to find wether the click event is sent from the button itself or the span inside of it and replace the buttons class accordingly

submit(event) {
    let prevColor = this.color;
    if (this.color === 'primary') {
            this.color = 'light'
    } else {
            this.color = 'primary'
    }

    if (event.target.localName === 'button') {
        event.target.className =event.target.className.replace('button-md-' + prevColor, 'button-md-' + this.color);
    } else if (event.target.parentElement.localName === 'button') {
        event.target.parentElement.className = event.target.parentElement.className.replace('button-md-' + prevColor, 'button-md-' + this.color);
    }
}

Upvotes: 2

Related Questions