【问题标题】:How to change the button color on click?单击时如何更改按钮颜色?
【发布时间】:2019-05-20 00:11:32
【问题描述】:

我在点击图标时更改了图标按钮颜色,默认图标按钮颜色是原色,当我点击图标按钮时,它应该将原色更改为红色。这对我来说工作正常,现在单击隐藏按钮后将显示一个是取消按钮,另一个是保存按钮到这里它现在工作正常,当我单击取消按钮时,红色按钮应该变为主要但取消按钮正在关闭并且标志性按钮的颜色没有改变

<kendo-grid-command-column headerClass="data-list-header-cell" title="Delete" width="5" filterable="false">
    <ng-template kendoGridCellTemplate let-site>
      <button mat-icon-button color="primary" (click)="onDelete(data)" [ngClass]="{'selectedRemoveButton':data.isClicked}">
        <mat-icon>remove_circle</mat-icon>
      </button>
      
      // these are icon button if clicked on this button it will change color and also show 2 buttons cancel and save.
      
      <ng-container *ngIf="showButtons">
    <span class="rightButtons">
      <button class="mat-button menu-button" (click)="cancel()">
        <mat-icon>block</mat-icon> CANCEL
      </button>
      <button class="mat-button primary-button" (click)=" save()">
        SAVE
      </button>
    </span>
  </ng-container>
.selectedRemoveButton {
  color: red
}
 onDelete(data: any) {
    if (data.isClicked) {
      this.dataList.push(data);
    }
    data.isClicked = !data.isClicked;
    this.showButtons = !this.showButtons;
    console.log(data.Id);
  }
  
  //these is where i am first clicking on button when i click on these button color will change to red
  
  cancel(): void {
    this.showButtons = false;
  }
  //if presse on cancel button is disappearing but color have to change red to primary
  save() {
   
      this.Service.datalist(data.Id).subscribe(
          data => {
            this.dataList = data;
            console.log(data);
          });
    
  }
  //this is save button 

请帮帮我

【问题讨论】:

  • tip:推荐使用renderer2 API 进行DOM操作

标签: html css angular typescript angular6


【解决方案1】:

使用ngClass 动态添加类。

<button class="mat-button menu-button" [ngClass]="removeStyles" (click)="cancel()">

removeStyles = "";
cancel(): void {
  this.showButtons = false;
  this.removeStyles= "selectedRemoveButton"
}

【讨论】:

  • 实际上,我需要从 HTML 应用的原色,在这种情况下,我无法为取消按钮编写 CSS
  • this.removeStyles= "primary-button"
【解决方案2】:

如果你没有得到改变是因为你错过了那里的一些东西。 尝试在单击按钮时添加一个变量,就像这样。

[ngClass]="changBtnColor ? classNameColorActual : classNameColorAfterClick" (click)="changeColor()"
.classNameColorActual{ color:red} 
.classNameColorAfterClick{color:blue} 

函数的意思

changeColor(): void {
     this.changBtnColor = !this.changBtnColor ;     // this should change the color of the 
                                     // button every time is clicked
  }

您应该使用自定义类来为它们提供样式,但如果您不想要它,您还应该使用元素的本地类来实现这一点,请转到 chrome 中的开发工具并搜索该类。 希望对你有帮助。

【讨论】: