I have this object valuesColors
that I use in a function
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;
}
}
In HTML, inside a loop I change style using getColor
function
<div [style.background-color]="getColor(title.value)" class="badge circle-indicator"></div>
I get this error:
ERROR TypeError: Cannot read property 'find' of undefined
I have this object valuesColors
that I use in a function
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;
}
}
In HTML, inside a loop I change style using getColor
function
<div [style.background-color]="getColor(title.value)" class="badge circle-indicator"></div>
I get this error:
Share Improve this question asked Aug 9, 2018 at 15:23 infodevinfodev 5,26522 gold badges81 silver badges152 bronze badges 3ERROR TypeError: Cannot read property 'find' of undefined
-
2
Shouldn't it be
valuesColors = you array
? – Madhan Varadhodiyil Commented Aug 9, 2018 at 15:28 - you probably meant to set the variable inside constructor? – Bhojendra Rauniyar Commented Aug 9, 2018 at 15:33
- Also , your array has syntax errors – Madhan Varadhodiyil Commented Aug 9, 2018 at 15:34
4 Answers
Reset to default 3You have to use =
instead of :
:
valuesColors = [
{
key: "<75%",
color: "#00965E"
},
{
key: ">=75%&<90%",
color: "#ff9933"
},
{
key: ">90%",
color: "#E61D00"
}
];
:
defines an object type whereas =
gives it some value. (be aware of the ,
instead of the ;
in your array)
so :
(docs) is used to set the type of the variable , So it must have been valuesColors:Array = your array
And your objects must be terminated by ,
not ';'
Your array must look something like this :
valuesColors = [
{
key: "<75%",
color: "#00965E",
},
{
key: ">=75%&<90%",
color: "#ff9933",
},
{
key: ">90%",
color: "#E61D00",
}
];
demo : https://stackblitz./edit/angular-fyo9q2 Hope this helps
I think that this
is referencing the getColor
method in this case. Does it still happen if you instead write it as getColor = (value) => {...}
?
You will need to bind your method to your class if you are calling it from another context. You could do this in your constructor:
constructor() {
this.getColor = this.getColor.bind(this);
}
That way, when something else calls your method, your use of this
within getColor
is preserved and will have access to your class property.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745514463a4630920.html
评论列表(0条)