在Angular 4中动态设置背景图像的推荐方法是什么

问题描述:

当前,我使用嵌入式样式设置图像背景.

Currently I'm setting the image background using inline-style.

<div [ngStyle]="{background: 'url(' + section.backgroundSrc + ') no-repeat'}">

但是,我正在寻找一种更清洁的方法...可能类似于通过角度在外部样式表中动态设置路径.但是,我不确定该怎么做.

However, I'm looking for a more cleaner approach...maybe something like dynamically setting the path in the external stylesheet through angular. However, I'm not sure how it can be done.

您无法在CSS文件中执行此操作.但是,您可以使当前代码不再那么冗长:

You can't do it thourgh CSS files. However, you can make your current code little less verbose :

<div [style.background]="'url(' + section.backgroundSrc + ') no-repeat'"></div>

如果angular抛出安全性错误,那么您也必须进行清理.因此,您将执行以下操作: 在HTML文件中-

If angular throws security errors, you will have to sanitize too. So you will do something like this: in HTML file-

<div [style.background]="background"></div>

在您的TS文件中

this.background= 
this.sanitization.bypassSecurityTrustStyle(`url(${this.section.backgroundSrc}) no-repeat`);