2017-07-11 185 views
0

的onclick改变特定的按钮颜色这是我的HTML样本:在离子2

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

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

+0

你能给细节,哪些按钮的类型,什么会被打回原形 – Skeptor

+0

它是一个过滤的搜索页面我开发toggable按钮的列表。所有的按钮都应该具有相同的样式,(我在_variables.scss文件中设置的主要颜色),但是单击时,它应该更改为浅色变量,这就是代码所做的。但它正在改变所有按钮的ionicNamedColor变量的值,而不仅仅是那一个。 –

回答

1

尝试发送$事件您切换功能

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

谢谢!这工作。 –