Typescript文件中获取有角度的背景颜色并将其绑定到我的h

Typescript文件中获取有角度的背景颜色并将其绑定到我的h

本文介绍了如何从Typescript文件中获取有角度的背景颜色并将其绑定到我的html页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用打字稿填充的数组,并且基于该数组中的值,我想为div设置不同的背景颜色,但是它不起作用.我在做什么错了?

I have an array that is being populated in typescript and based on the value in the array, I want to set a different background color for my div but it's not working. What am I doing wrong?

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

I've tried to set the background using [style.backgroundColor]="statusColor[i]". statusColor is an array declared in my typescript. It works normally if I try to bind it without an array to a single object as below:[style.backgroundColor]="statusColor". This is the error I'm getting:Cannot read property '0' of undefined

这是代码:这是我的json对象的接口:

Here is the code:This is my interface for the json object:

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

这是我主要组件的打字稿:

This is the typescript for my main component:

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

在数组中填充投诉后,我使用此功能设置颜色:

After the complaints are populated in the array I use this function to set the color:

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>

我希望背景颜色根据状态改变.

I want the background color to change based on the status.

推荐答案

按以下方式尝试ngStyle

Try ngStyle as follows

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

这篇关于如何从Typescript文件中获取有角度的背景颜色并将其绑定到我的html页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:23