Dynamically change button color

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;
  }
1 Like

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.

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

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.

But how to access colors array from a component?

Just as strings

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

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

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.

20 characters min…

2 Likes

Yes, thank you this is working!

1 Like

Hello,
I can also take this way

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

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

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

1 Like

not working!.
works before changing. and the function changes the variable but ui is not updated;