how to use correctly [ngStyle] with function

杀马特。学长 韩版系。学妹 提交于 2019-12-11 10:33:09

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/50634162/how-to-use-correctly-ngstyle-with-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!