如何正确使用带有功能的[ngStyle] [英] how to use correctly [ngStyle] with function

查看:310
本文介绍了如何正确使用带有功能的[ngStyle]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下错误,不断向我返回调试控制台

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

HomeComponent.html:33错误TypeError:无法读取未定义的属性"url" 在HomeComponent.getImageEvent(home.component.ts:73) 在Object.eval [作为updateDirectives](HomeComponent.html:33)

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

推荐答案

看到的时候:

无法读取未定义的属性"url"

Cannot read property 'url' of undefined

这表示未定义.也就是说,您要读取属性的对象(在这种情况下为"url")没有定义.

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

尝试使用某种isset().在javascript中,您可以通过几种方法对其进行排序.

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

我对数组的建议是myArr[0] !== undefined,对于对象,可以使用hasOwnProperty('url').或者只是将简短版本与||一起使用:

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

javascript isset()此处了解更多信息

这篇关于如何正确使用带有功能的[ngStyle]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆