在Ionic 2中更改特定按钮颜色

时间:2017-07-11 17:45:59

标签: angular typescript ionic-framework ionic2

这是我的html示例:

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

我这里有一个大约12个按钮的列表,我想让它们的颜色在单击时单独更改,所有按钮都共享相同的方法。这是打字稿:

export class PopoverComponent {


public ionicNamedColor: string = 'primary';

constructor() {
}

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

问题:现在这个代码使所有按钮在单击任何按钮时都会改变颜色。我怎样才能改变这一点,只更改特定按钮,而不是更改所有其他按钮的变量?

1 个答案:

答案 0 :(得分:2)

尝试将$ event发送到您的切换功能

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

然后在你的函数中你需要找到从按钮本身或其内部的跨度发送的click事件并相应地替换按钮类

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);
    }
}