所以我想了一个答案,而不必使用函数来获取 HTML 中的样式,同时仍然没有预定义的角色。
您可以为您的成员添加一个颜色属性,这将基于成员的角色。假设您在制作组件之前知道成员和颜色,您可以在ngOnInit() 中设置它,如下所示:
ngOnInit() {
this.assignColorsToMembers();
}
assignColorsToMembers() {
const uniqueRoles = this.getUniqueRoles();
const rolesWithColors = this.assignColorsToRoles(uniqueRoles);
this.members.forEach(member => {
member.color = rolesWithColors[member.role];
});
}
getUniqueRoles(): string[] {
const allRoles = this.members.map(member => member.role);
const uniqueRoles = Array.from(new Set(allRoles));
return uniqueRoles;
}
assignColorsToRoles(roles: string[]): RolesWithColors {
const rolesWithColors = {};
roles.forEach((role, index) => {
rolesWithColors[role] = this.colors[index];
});
return rolesWithColors;
}
接口:
interface RolesWithColors {
[key: string]: string;
}
interface Member {
name: string;
role: string;
color?: string;
}
在 getUniqueRoles() 中,您创建一个数组,获取所有成员的角色,然后删除重复项。在 assignColorsToRoles() 中,您创建一个对象,其中键(属性)是您在 getUniqueRoles() 中创建的数组中的角色,值是您的颜色数组中的颜色。
这假设您有一个颜色与此类似的数组:colors = ['red', 'yellow', 'blue', 'green', 'purple'];,并且您的颜色数组的长度足以为每个角色赋予不同的颜色。
如果你的颜色数组不够长,你可以在函数中检查:
assignColorsToRoles(roles: string[]): RolesWithColors {
const rolesWithColors = {};
roles.forEach((role, index) => {
if (this.colors.length < index + 1) {
rolesWithColors[role] = 'white';
}
rolesWithColors[role] = this.colors[index];
});
return rolesWithColors;
}
当然,您可以用白色代替您想要的任何其他颜色。
如果您已经将颜色与某些角色相结合,这将简单得多。您可以省略 assignColorsToMembers 的前两个步骤,并根据您的角色和颜色的保存方式(数组或对象)更改其余步骤。
现在所有成员都有一个颜色分配给他们,你可以在你的 html 中使用这个属性:
<div *ngFor="let member of members" [style.background-color]="member.color">
{{member.name}}
</div>