【问题标题】:Dynamic background color for span tagspan 标签的动态背景颜色
【发布时间】:2020-11-06 00:32:52
【问题描述】:

我正在尝试为包含文档类型的 Angular 视图中的 span 标签添加动态背景颜色。给出以下源代码:

<mat-card *ngFor="let record of records">
  <span class="doc-id">
    Document ID: {{ record.id }}
  </span>
  <span>
    {{ record.documentType }}
  </span>
</mat-card>

record.documentType 可以是任何东西(仅限字符串),它来自后端。目标是为相同的文档类型添加动态背景颜色。

例如:

如果 documentType 是“employee”,那么所有员工类型都应该是随机颜色(比如说绿色)。如果是“工资”,那么所有工资类型都应该是不同的随机颜色(比如说黄色)。

我尝试使用在 Google 上找到的不同解决方案,但都不够好。

我正在考虑将 documentType 值传递给 typescript 函数,如果尚未为该类型生成一个新的随机颜色,它将生成一个新的随机颜色。

[ngStyle]="generateRandomBackgroundColor(record.documentType)

对于此类问题,您有什么建议和最佳做法吗?我在项目中使用 sass,所以如果有与 sass 相关的建议,我也很乐意阅读。

提前致谢!

【问题讨论】:

    标签: angular typescript sass


    【解决方案1】:
    @Pipe({
      name: 'randomColor',
    })
    export class RandomColorPipe implements PipeTransform {
      private static readonly colors: Map<string, string> = new Map();
    
      /**
       * Generates random hex color
       * https://css-tricks.com/snippets/javascript/random-hex-color/
       */
      private getRandomColor(): string {
        return Math.floor(Math.random() * 16777215).toString(16);
      }
    
      public transform(id: string): string {
        const color = RandomColorPipe.colors.get(id) ?? this.getRandomColor();
    
        if (!RandomColorPipe.colors.has(id)) {
          RandomColorPipe.colors.set(id, color);
        }
    
        return color;
      }
    }
    
    <mat-card *ngFor="let record of records">
      <span class="doc-id">
        Document ID: {{ record.id }}
      </span>
      <span [style.backgroundColor]="'#' + (record.documentType | randomColor)">
        {{ record.documentType }}
      </span>
    </mat-card>
    

    【讨论】:

    • 这很好用,谢谢。但是,文本的颜色有时没有足够的对比度,因此不可读,因此无法访问。你知道如何解决这个问题吗?
    • 你先生太棒了。奇迹般有效。 :)
    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 2011-12-18
    • 2019-10-14
    • 2016-05-15
    • 1970-01-01
    相关资源
    最近更新 更多