4

I have the following error that constantly returns me the debug console

HomeComponent.html:33 ERROR TypeError: Cannot read property 'url' of undefined at HomeComponent.getImageEvent (home.component.ts:73) at Object.eval [as updateDirectives] (HomeComponent.html:33)

HomeComponent.html

<div [ngStyle]="getImageEvent(i)">

home.component.ts

getImageEvent(index: number): object {
 return {'background-image': 'url(' + this.events[index].images[0].url + ')'};
}
Gabriel Sule
  • 373
  • 6
  • 17
  • The issue might be inside your array. Any chances your `images[0]` not have the `url` property? Or the images array be empty? try `console.log(this.events[index].images)` and see what shows up – Leo Caseiro Jun 01 '18 at 00:16
  • Thank you very much for the help you gave me, do not really consider that bug, sometimes you do not see the essentials !! – Gabriel Sule Jun 01 '18 at 00:38

2 Answers2

3

When you see:

Cannot read property 'url' of undefined

It means something is undefined. Which means, the object you are trying to read the property (in that case 'url') is not defined.

Try use some kind of isset(). In javascript you have a few ways to sort that.

My recommendation for arrays is myArr[0] !== undefined, for objects, you can use hasOwnProperty('url'). Or just use the short version with || :

getImageEvent(index: number): object {
    const img = this.events[index].images[0] || {}; // is array defined?
    const imgSrc = img.url || ''; 
    return {'background-image': 'url(' + imgSrc + ')'};
}

Read more about javascript isset() here

Leo Caseiro
  • 1,667
  • 1
  • 22
  • 35
1

You can do the same thing in the template using the ? operator. The ? operator makes everything after it optional so that you don't get an error trying to read something that is undefined.

<div [style.background-image]="'url('+events[i].images[0]?.url+')'">
Reactgular
  • 52,335
  • 19
  • 158
  • 208