如何更改事件上的按钮颜色?

How to change the buttons color on an event?

我想在活动中更改我的按钮颜色。我尝试了 2 种方法,但都失败了。使用第一个选项,我什至无法再启动该应用程序,使用第二个选项,颜色就不会改变。

1。 HTML

<ion-button [color]="done ? 'primary' : 'danger'"> </ion-button>

TS

public done: boolean = true;

func() { 
this.done = !this.done;
}

2。 HTML

     <ion-button (click)="toggleNamedColor()"></ion-button>

TS

public ionicNamedColor: string = 'light';
public ionicNamedColor2: string = 'primary';

public toggleNamedColor(): void {
  if(this.ionicNamedColor === 'light') { 
    this.ionicNamedColor = 'primary'
  } else {
    this.ionicNamedColor = 'light'
  }

您可以使用 ngStyle 指令来做到这一点。 Here's 同样的 stackblitz。

.ts

export class AppComponent  {
  toggle: boolean;

  toggleColor() {
    this.toggle = !this.toggle;
  }
}

.html

<button (click)="toggleColor()"
        [ngStyle]="{
          'background-color' : toggle ? 'yellow' : 'pink'
        }"
>Click me</button>

编辑:不要这样做

我会这样做:

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

然后在returns后面写一个你想要的颜色的代码:

getColor(): string {
  return this.done ? 'primary' : 'danger';
}

看看Stackblitz

.ts 文件

export class AppComponent  {
  name = 'Angular';
  toggle: boolean ;
  propColor:string ='red' ;

  changeColor() {
    this.toggle = !this.toggle;
    if(this.toggle ==true){
      this.propColor = 'blue'

    }else{
      this.propColor = 'red'
    }

    //console.log(this.toggle);
  }
}

html 模板

<button (click)="changeColor()"
        [ngStyle]="{
          'background-color' :  propColor 
        }"
>Toggle Color</button>