Javascript 无法读取属性';查找';在角度上未定义的
我有一个在函数中使用的对象Javascript 无法读取属性';查找';在角度上未定义的,javascript,angular,Javascript,Angular,我有一个在函数中使用的对象值colors export class CountryEnvelopeComponent implements OnInit { constructor() {} valuesColors: [ { key: "<75%"; color: "#00965E"; }, { key: ">=75%&<90%"; color: "#ff993
值colors
export class CountryEnvelopeComponent implements OnInit {
constructor() {}
valuesColors: [
{
key: "<75%";
color: "#00965E";
},
{
key: ">=75%&<90%";
color: "#ff9933";
},
{
key: ">90%";
color: "#E61D00";
}
];
ngOnInit() {
}
getColor(value) {
console.log(this.valuesColors);
let element = this.valuesColors.find(elm => {
return elm.key == value;
});
return element.color;
}
}
<div [style.background-color]="getColor(title.value)" class="badge circle-indicator"></div>
我得到这个错误:
错误类型错误:无法读取未定义的属性“find”
我认为
this
在本例中引用了getColor
方法。如果您将其改为getColor=(value)=>{…}
,是否仍会发生这种情况?您必须使用=
而不是:
:
值颜色=[
{
关键字:“=75%和90%”,
颜色:“E61D00”
}
];
:
定义一个对象类型,而=
赋予它一些值。(注意数组中的,
而不是;
)如果从其他上下文调用方法,则需要将其绑定到类。您可以在构造函数中执行此操作:
constructor() {
this.getColor = this.getColor.bind(this);
}
这样,当其他对象调用您的方法时,您在getColor
中使用的this
将被保留,并将有权访问您的类属性。因此:
()用于设置变量的类型,因此它必须是值颜色:数组=您的数组
并且您的对象必须以,
而不是“;”终止
您的阵列必须如下所示:
valuesColors = [
{
key: "<75%",
color: "#00965E",
},
{
key: ">=75%&<90%",
color: "#ff9933",
},
{
key: ">90%",
color: "#E61D00",
}
];
值颜色=[
{
关键字:“=75%和90%”,
颜色:“E61D00”,
}
];
演示:
希望这有帮助是不是应该是
valuesColors=you array
?您可能想在构造函数中设置变量?而且,您的数组有语法错误