Gabriel Sule
Gabriel Sule

Reputation: 383

how to use correctly [ngStyle] with function

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 + ')'};
}

Upvotes: 5

Views: 11478

Answers (2)

Reactgular
Reactgular

Reputation: 54771

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

Upvotes: 1

Leo Caseiro
Leo Caseiro

Reputation: 1845

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

Upvotes: 3

Related Questions