在Angular 4中动态设置背景图像的推荐方法是什么 [英] What is the recommended way to dynamically set background image in Angular 4

查看:400
本文介绍了在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`);

这篇关于在Angular 4中动态设置背景图像的推荐方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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