简体   繁体   English

使用 [ngStyle] 将自定义颜色应用于 mat-raised-button

[英]Using [ngStyle] to apply custom color to mat-raised-button

I want to use a custom mat-button color style but it's not working when I combine it with an [ngStyle].我想使用自定义的 mat-button 颜色样式,但是当我将它与 [ngStyle] 结合使用时它不起作用。

This is what I want:这就是我要的:

html: 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: css:

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

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

The transform is working fine but the color is not.转换工作正常,但颜色不是。

typescript:打字稿:

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;
}

The html below works so the custom mat-button color is working.下面的 html 有效,因此自定义 mat-button 颜色有效。

html: 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>

I could use an *ngIf="isActiveDirection(label, directionValue)" and have two button elements.我可以使用 *ngIf="isActiveDirection(label, directionValue)" 并有两个按钮元素。 One with color="arrow-selected" and the other with color="arrow-deselected" but the cleaner solution would be via the [ngStyle].一个是 color="arrow-selected",另一个是 color="arrow-deselected",但更简洁的解决方案是通过 [ngStyle]。 So I would be very happy if this is possible.所以如果可以的话,我会很高兴。

All help or tips are welcome.欢迎所有帮助或提示。

I presume your theme has those color names in it?我想你的主题中有那些颜色名称? The color attribute is special for the material controls. color属性是材质控件的特殊属性。 It is not CSS.它不是 CSS。 ngStyle returns CSS. ngStyle返回 CSS。

Try:尝试:

<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>

You'll need another function to get the colour name:您需要另一个函数来获取颜色名称:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM