首页 > 解决方案 > 使用 [ngStyle] 将自定义颜色应用于 mat-raised-button

问题描述

我想使用自定义垫按钮颜色样式,但是当我将它与 [ngStyle] 结合使用时它不起作用。

这就是我要的:

html:

<button mat-raised-button
        [ngStyle]="getDirectionArrowStyle(item.label, 'ltr')"
        value="ltr"
        aria-label="Left To Right"
        (click)="setActiveDirection(item.label, 'ltr')">
   <mat-icon>east</mat-icon>
</button>

CSS:

.mat-arrow-selected {
  background-color: green;
  color: #fff;
}

.mat-arrow-deselected {
  background-color: red;
  color: #fff;
}

转换工作正常,但颜色不是。

打字稿:

getDirectionArrowStyle(label: string, directionValue: string) {
  const isActiveDirection = this.isActiveDirection(label, directionValue);
  const styles = {
    color: isActiveDirection ? 'arrow-selected' : 'arrow-deselected',
    transform: isActiveDirection ? 'scale(1.2)' : 'scale(0.5)'
  };
  return styles;
}

下面的 html 可以正常工作,因此自定义 mat-button 颜色可以正常工作。

html:

<button mat-raised-button
        color="arrow-selected"
        value="ltr"
        aria-label="Left To Right"
        (click)="setActiveDirection(item.label, 'ltr')">
   <mat-icon>east</mat-icon>
</button>

我可以使用 *ngIf="isActiveDirection(label, directionValue)" 并有两个按钮元素。一个颜色=“箭头选择”,另一个颜色=“箭头取消选择”,但更清洁的解决方案是通过[ngStyle]。因此,如果可以的话,我会非常高兴。

欢迎所有帮助或提示。

标签: angular

解决方案


我想您的主题中有那些颜色名称?该color属性对于材质控件是特殊的。它不是 CSS。ngStyle返回 CSS。

尝试:

<button mat-raised-button
        [ngStyle]="getDirectionArrowStyle(item.label, 'ltr')"
        [color]="getDirectionColour(item.label, 'ltr')"
        value="ltr"
        aria-label="Left To Right"
        (click)="setActiveDirection(item.label, 'ltr')">
   <mat-icon>east</mat-icon>
</button>

您需要另一个函数来获取颜色名称:

getDirectionColour(label: string, directionValue: string) {
  const isActiveDirection = this.isActiveDirection(label, directionValue);
  return isActiveDirection ? 'arrow-selected' : 'arrow-deselected';
}

推荐阅读