span标记的动态背景色



我正在尝试为包含文档类型的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",那么所有员工类型都应该是随机颜色(比如绿色(。如果是"工资",那么所有的工资类型都应该是不同的随机颜色(比如黄色(。

我试过使用谷歌上的不同解决方案,但都不够好。

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

[ngStyle]="generateRandomBackgroundColor(record.documentType)

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

提前感谢!

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

最新更新