Dynamic change color of button for specific button


#1
    <ion-col col-3>
                <button ion-button (click)="onPunchPress($event)"><span>1</span></button>
            </ion-col>
            <ion-col col-3>
                <button ion-button (click)="onPunchPress($event)"><span>2</span></button>
            </ion-col>

How can I change color of specific button? Suppose If I click on 1st button then what to do that only it’s
[color] attributre is changed from “light” to “danger” ?
Please help urgent need!


#2

have you tried ngClass attribute?


#3

ngClass will change for all buttons,

I want to change only clicked buttons class or color attribute. Toggle class on each and every button.


#4

no brother, it will not change for all buttons.
you have to set condition in ngclass

declare any variable in ts file such as : btnCurrent : int = 0

then in html file set the value of btnCurrent on button click event such as :
<button ion-button (click)="btnCurrent =1"><span>1</span></button>
<button ion-button (click)="btnCurrent =2"><span>2</span></button>

and in ngClass put condition according to btnCurrent such as :
<button ion-button ngClass="{ 'yourcssclass': btnCurrent ==1}" (click)="btnCurrent =1"><span>1</span></button>
<button ion-button ngClass="{ 'yourcssclass': btnCurrent ==2}" (click)="btnCurrent =2"><span>2</span></button>


#5

If button 1 was pressed then button 2 pressed. Button 1 color change must be there. That not need to be change means toggle on click of each and every button bro.


#6

then you can take unique varible for every button and check it in ngClass!!


#7

How? Can you show me little demo? You means somehting like btnCurrent ,btnCurrent1,btnCurrent3? Is that good logic?


#8

and to apply toggle effect u have to take boolean variable and set value on click event such as :
(click)=" btn1= !btn1"


#9

there is no other way to achieve it because i waste 1 week for this topic


#10

Oops! We can’t do some thing like (click)=“somefunction($event)” on button click? And add [color] attribute to that button based on event? Means like jquery we can add attribute and remove attribute (classes too) ? toggle?


#11

yes, you can
but using jquery it may be a long process to achieve toggle effect and all other stuff and you haave to do R&D on google for it !!


#12

Yup, But all the things will be dynamic then.

Process will be :slight_smile:


(click)="myfunc($event)"

myfunc(e){
// add attr if not exists
//remove attr if exists
if(){
// if attr, then func based on it.
}
else{
// if not attr, then func based on it.
}
}

#13

this is basic jqury to do

$(this).css('background-color', 'blue');


#14
somefunction(e)
{
e.attr("color","light");
e.attr("color","danger");
}

YES!!!


#15

may be because i dont have enough knowledge about jquery. i used basic jquery thats it


#16

Thanks bro, you have helped me alot!


#17

Not working!!!