场景:
我的 Angular 应用程序中有一个元素,我想为其添加背景图像。目前我有这个:
<div class={{background-class}}></div>
例如,background-class
是“background-style-1”,它在我的样式表中是这样的:
background-style-1 {
background-image: url(../../../../assets/images/contextmenu/person.png);
}
问题:
我不想将所有背景图片 URL 硬编码到我的样式表中。相反,我只想将 URL 传递到 HTML 标记中。
我尝试过的
<div style="background-image: url(../../../../assets/images/contextmenu/person.png)"></div>
这无法显示图像,当我查询元素时,它显示:
我想知道的:
为什么将图像 URL 作为内联样式属性传递不起作用,我该如何让它起作用?
最佳答案
您可以使用以下语法从 html 动态设置背景图像:[style.someproperty]="'somevalue'"
。在您的情况下,它可能看起来像这样。
<div [style.backgroundImage]="'url(' + url + ')'"></div>
这会将 url
的值(在您的 Controller 中定义)作为背景图片的 url。
关于html - Angular:如何通过 HTML 而不是 CSS 传递背景图片 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395987/