Angular Material mat-chip 上的文本颜色

问题描述 投票:0回答:2

我有一个

mat-chip-set
和几个带有自定义
mat-chip
类的
product-chip
对象:

<mat-chip-set>
  <mat-chip class="product-chip" *ngFor="let category of categories">
    {{category}}
  </mat-chip>
</mat-chip-set>

我的CSS是:

.product-chip {
  background-color: pink !important;
  color: white !important;
}

结果是芯片背景颜色是我想要的粉红色,但文字颜色仍然是黑色。

如何将

mat-chip
对象的文本颜色设为白色?

参见 StackBlitz 示例:https://stackblitz.com/edit/angular-nzhkmg?file=src/app/chips-overview-example.html

angular material-ui angular-material
2个回答
10
投票

我会编辑使用的变量。

style.css

.mat-mdc-standard-chip {
  --mdc-chip-label-text-color: #fff;
}

此外,检查其他选项的作用,以在芯片处于其他状态(禁用)时保持样式一致。

.mat-mdc-standard-chip {
  --mdc-chip-elevated-container-color: #e0e0e0;
  --mdc-chip-elevated-disabled-container-color: #e0e0e0;
  --mdc-chip-label-text-color: #fff;
  --mdc-chip-disabled-label-text-color: #212121;
  --mdc-chip-with-icon-icon-color: #212121;
  --mdc-chip-with-icon-disabled-icon-color: #212121;
  --mdc-chip-with-trailing-icon-disabled-trailing-icon-color: #212121;
  --mdc-chip-with-trailing-icon-trailing-icon-color: #212121;
  --mdc-chip-with-icon-selected-icon-color: #212121;
}

示例:https://stackblitz.com/edit/angular-nzhkmg-dk3hsm?file=src%2Fstyles.scss


0
投票

您可以创建一个指令,将文本和背景颜色作为输入,例如如下:

chip-theme.directive.ts

import { Directive, ElementRef, Input, OnInit } from '@angular/core';

type ChipTheme = {
  backgroundColor: string;
  color: string;
};

@Directive({
  selector: '[appChipTheme]',
})
export class ChipThemeDirective implements OnInit {
  @Input('appChipTheme') theme: ChipTheme;

  constructor(private el: ElementRef) {}

  ngOnInit(): void {
    const natEl = this.el.nativeElement;
    const { color, backgroundColor } = this.theme;
    // Background Color
    natEl.style.backgroundColor = backgroundColor;
    // Text Color
    natEl.style.setProperty('--mdc-chip-label-text-color', color);
  }
}

然后在 HTML 模板中使用如下:

<mat-chip
  *ngFor="let chip of chips"
  [appChipTheme]="{
    color: chip.color,
    backgroundColor: chip.bgColor
  }">
  <span>{{ chip.text }}</span>
</mat-chip>

不要忘记在 app.module.ts 中导入指令。

© www.soinside.com 2019 - 2024. All rights reserved.