【问题标题】:Change color of button with mat-icon with a click [duplicate]通过单击更改带有 mat-icon 按钮的颜色 [重复]
【发布时间】:2019-07-06 00:38:42
【问题描述】:

所以我需要在单击时更改带有材质图标的按钮的颜色。我试过这样的事情:

HTML:

  <button (click)="activeSkill($event)" color="primary" mat-mini-fab>
    <mat-icon aria-label="" name='skill1'>euro_symbol</mat-icon>
  </button>

TS:

activeSkill(event){
    event.target.setAttribute('color', 'accent');
}

但这不起作用。哪种方法更简单?实际上,如果可能的话,我如何不使用默认的原色和强调色,而是使用一组颜色。

【问题讨论】:

  • 我没有正确写出我的疑问,你是对的,对于上面的问题,这是一个很好的解决方案。

标签: html angular sass angular-material


【解决方案1】:

您还可以执行以下操作。在按钮标签中添加引用#button

<button (click)="activeSkill()" color="primary" mat-mini-fab #button>
  <mat-icon aria-label="" name='skill1'>add</mat-icon>
</button>

在你的组件中使用 ViewChild 装饰器

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('button') button: ElementRef;

  activeSkill() {
    (<any>this.button).color = 'accent';
  }
}

看到这个StackBlitz

【讨论】:

    【解决方案2】:

    您可以使用该变量并使用该变量来设置颜色值按钮

    下面是一个例子

    在 HTML 中,

    <button (click)="selectedColor = 'accent'" [color]="selectedColor" mat-mini-fab>
        <mat-icon aria-label="" name='skill1'>euro_symbol</mat-icon>
     </button>
    

    在.ts中

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'button-overview-example',
      templateUrl: 'button-overview-example.html',
      styleUrls: ['button-overview-example.css'],
    })
    export class ButtonOverviewExample {
    
      selectedColor: string = 'primary';
    
    }
    

    【讨论】:

      【解决方案3】:

      您可以将局部变量作为 ref 传递。并像这样相应地设置样式 -

      activeSkill(event, ele) {
          console.log(event, ele);
          ele['_elementRef']['nativeElement']['className'] = 'mat-raised-button mat-accent';
        }
      
      <button #btn (click)="activeSkill($event, btn)" md-raised-button color="primary">Primary</button>
      

      Working example

      【讨论】:

      • 当里面有一个垫子图标时,这不能正常工作,垫子图标是一个圆形按钮,变成了一个平面按钮并失去了它的属性。不过谢谢你的回答。
      • 是的,除此之外还有一些最佳答案。刚刚发布,如果没有办法尝试这个!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 2018-06-14
      • 2019-08-12
      • 2016-12-11
      • 2016-04-05
      相关资源
      最近更新 更多