5

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 + ')'};
}
2
  • 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 Commented Jun 1, 2018 at 0:16
  • Thank you very much for the help you gave me, do not really consider that bug, sometimes you do not see the essentials !! Commented Jun 1, 2018 at 0:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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+')'">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.