An alternative approach to achieve this, in a more ionic manner, is by utilizing the color attribute as demonstrated below:
@Component({...})
export class HomePage {
public ionicNamedColor: string = 'primary';
constructor() {}
public toggleNamedColor(): void {
if(this.ionicNamedColor === 'primary') {
this.ionicNamedColor = 'secondary'
} else {
this.ionicNamedColor = 'primary'
}
}
}
When implementing in your view:
<button (click)="toggleNamedColor()" ion-button [color]="ionicNamedColor">Click me!</button>
Note that you need to include the desired colors in the predefined named color variables from your variables.scss
:
$colors: (
primary: #488aff,
secondary: #32db64,
danger: #f53d3d,
light: #f4f4f4,
dark: #222
);
In case you prefer not using the named color variables, an option would be to directly modify the button's background color like so:
@Component({...})
export class HomePage {
public hexColor: string = '#000000';
constructor() {}
public toggleBackgroundColor(): void {
if(this.hexColor === '#000000') {
this.hexColor = '#dddddd'
} else {
this.hexColor = '#000000'
}
}
}
To implement this in your view:
<button (click)="toggleBackgroundColor()" ion-button [style.background-color]="hexColor">Click me!</button>
Please explore both methods further in this plunker.