infodev
infodev

Reputation: 5235

Cannot read property 'find' of undefined in Angular

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

Upvotes: 0

Views: 5002

Answers (4)

Madhan Varadhodiyil
Madhan Varadhodiyil

Reputation: 2116

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.com/edit/angular-fyo9q2 Hope this helps

Upvotes: 2

Steve Vaughan
Steve Vaughan

Reputation: 2189

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.

Upvotes: 0

Augustin R
Augustin R

Reputation: 7799

You 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)

Upvotes: 3

Sean D
Sean D

Reputation: 156

I think that this is referencing the getColor method in this case. Does it still happen if you instead write it as getColor = (value) => {...}?

Upvotes: 0

Related Questions