如何从angular中的typescript文件中获取背景色并将其绑定到html页面?
我有一个数组,它是用typescript填充的,基于数组中的值,我想为我的div设置一个不同的背景色,但它不起作用。我做错了什么 我尝试使用[style.backgroundColor]=“statusColor[I]”设置背景。statusColor是在我的typescript中声明的数组。如果我尝试在不使用数组的情况下将其绑定到单个对象,它将正常工作,如下所示: [style.backgroundColor]=“statusColor”。这就是我得到的错误: 无法读取未定义的属性“0” 代码如下: 这是我的json对象接口:如何从angular中的typescript文件中获取背景色并将其绑定到html页面?,html,css,angular,typescript,Html,Css,Angular,Typescript,我有一个数组,它是用typescript填充的,基于数组中的值,我想为我的div设置一个不同的背景色,但它不起作用。我做错了什么 我尝试使用[style.backgroundColor]=“statusColor[I]”设置背景。statusColor是在我的typescript中声明的数组。如果我尝试在不使用数组的情况下将其绑定到单个对象,它将正常工作,如下所示: [style.backgroundColor]=“statusColor”。这就是我得到的错误: 无法读取未定义的属性“0” 代码
export interface IComplaint {
id: string;
description: string
status: string
}
这是我的主要组件的类型脚本:
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]);
}
for(让i=0;i尝试如下ngStyle
[ngStyle]="{'background-color': statusColor[i]}
请尝试以下样式
[ngStyle]="{'background-color': statusColor[i]}
我认为装订的风格应该是:
[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 '';
}
}
}
}
由于您要遍历所有投诉数组,您只需将状态传入并通过管道传输即可。我认为样式绑定应该是:
[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 '';
}
}
}
}
由于您要循环查看所有投诉数组,您可以将状态传入并进行管道处理。嗯……与您的问题无关,但作为ICompaint[]
?如何处理投诉:ICompaint[]=[]?在这句话中还忘了一个分号:让投诉投诉让i=index
如果内存可用:[style.backgroundColor=“statusColor[i]”
应该是[style.backgroundColor]=“statusColor[i]”
另外,var i在这里。投诉
不是迭代数组的正确方法。是的,这也可以工作,但我也可以通过这种方式将JSON对象加载到投诉数组中。嗯……与您的问题无关,但是{}作为ICompaint[]
怎么样?在这句话中还忘了一个分号:让投诉投诉让i=index
如果内存可用:[style.backgroundColor=“statusColor[i]”
应该是[style.backgroundColor]=“statusColor[i]”
另外,var i在这里。投诉
不是迭代数组的正确方法。是的,这也可以,但我也可以通过这种方式将JSON对象加载到投诉数组中。