网站搜索

css - 我如何在 Angular 中从 TypeScript 文件获取背景颜色并绑定到我的 HTML 页面?


我有一个在 TypeScript 中被填充的数组,根据数组中的值,我想为我的 div 设置不同的背景颜色,但它没有起作用。我做错了什么?

我尝试使用 [style.backgroundColor]="statusColor[i]" 来设置背景。statusColor 是我在 TypeScript 中声明的数组。如果我尝试将其绑定到单个对象而不使用数组,如下:[style.backgroundColor]="statusColor",它可以正常工作。我得到的错误是:无法读取未定义的属性 '0'

这是代码:这是我为 JSON 对象定义的接口:

export interface IComplaint {
    id: string;
    description: string
    status: string
}

这是我的主组件的 TypeScript 文件:

public complaints = {} as IComplaint[];        
public statusColor: string[];

在将投诉填充到数组后,我使用此函数来设置颜色:

for (let i=0; i<this.complaints.length; i++) {
        if (this.complaints[i].status === "Reported")
          this.statusColor[i] = 'red';
        else if (this.complaints[i].status === "Resolved")
          this.statusColor[i] = 'green';
        else if (this.complaints[i].status === "In progress")
          this.statusColor[i] = 'yellow';
        console.log(this.statusColor[i]);
    }       

这是 HTML 代码:

<mat-card class="card" *ngFor="let complaint of complaints; let i = index">
<div class="status" [style.backgroundColor]="statusColor[i]">
                        {{ complaint.status }}
                </div>
</mat-card>

<div class="status" [style.backgroundColor]="statusColor[i]">
                            {{ complaint.status }}
                    </div>  

我希望背景颜色根据状态变化。

答案#1

尝试如下使用 ngStyle

[ngStyle]="{'background-color': statusColor[i]}

答案#2

我认为样式绑定应该是:[style.background-color]="statusColor[i]"

如果你想提高你的代码,我建议你使用管道来进行处理。管道对性能也非常友好。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'complaintBgColourPipe'
})
export class ComplaintBgColourPipe implements PipeTransform {
  transform(value: string): string {
    switch (value) {
      case 'Reported': {
        return 'red';
      }

      case 'Resolved': {
        return 'green';
      }

      case 'In progress': {
        return 'yellow';
      }

      default: {
        return '';
      }
    }
  }
}

既然你要遍历你的所有 complaints 数组,你可以直接传入状态并进行管道处理。