Dynamically change button color


#1

How can I change the button color dynamically ? Something like code below as an example:

<button ion-button [color]="getColor()"></button>

getColor(){
    let color = '#ba1488';
    return color;
  }

#2

You could add buttonColor as a property to your class, and just change the value of that. And in your html do

<button ion-button [color]="buttonColor" (click)="someAction()"></button>

ts

class AComponent {
    private buttonColor: string = "#000";

    someAction() {
        this.buttonColor = "#fff";
    }
}

Edit: I just realized, doesn’t the color binding look up a color in the SCSS colors array? Not sure if it falls back to using the input as a hex, let me know if this works.


#3

It doesn’t work, the color is just set to primary this way.


#4

Then you can

A. Make classes for your colors and do

<button ion-button [ngClass]="buttonClass" (click)="someAction()"></button>

B. Set the styling directly

<button ion-button [style.backgroundColor]="buttonColor" (click)="someAction()"></button>

Or C. Add the colors you wish to use in the colors array, and have buttonColor return the name of the color in that array.


Change button text or button color onclick ionic v3
#5

But how to access colors array from a component?


#6

Just as strings

<button ion-button [color]="buttonColor" (click)="someAction()"></button>
class AComponent {
    private buttonColor: string = "primary";

    someAction() {
        this.buttonColor = "light";
    }
}

#7

It is still being set just to primary color, how can I use hex colors to do that?

The colors are being generated during the work of my app, so I have to assign it dynamically from my component.


#8

20 characters min…


#9

Yes, thank you this is working!


#10

Hello,
I can also take this way

<button  [className]="btnColors">btn title</button> 

export class anyComponent {
@Input() btnColors = 'btn btn-warning';
 constructor() {}
}

#11

What if have, for example, 5 elements? I dont want to create 5 different variables for that…