angular4 的动态style之background-image

本文介绍如何在Angular中使用样式绑定来动态设置元素的背景图片,特别是当图片为Base64编码时的方法。通过使用DomSanitizer绕过安全限制,确保了应用的安全性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考angualr4之background-image的问题

Style binding

You can set inline styles with a style binding.

Style binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix style, followed by a dot (.) and the name of a CSS style property: [style.style-property].

src/app/app.component.html
content_copy<button [style.color]="isSpecial ? 'red': 'green'">Red</button>
<button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>

Some style binding styles have a unit extension. The following example conditionally sets the font size in “em” and “%” units .

src/app/app.component.html
content_copy<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button>
<button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>

While this is a fine way to set a single style, the NgStyle directive is generally preferred when setting several inline styles at the same time.

官方的文档很清楚,利用[style.styleAtribute] = "styleAtributeVar"

在项目中碰到一个问题,想到哪个台改变background-image,并且从后端获取的image的url是base64位的,怎么展示呢?

开始利用<div [style.background-image]="bgpictrue">,在ts文件中

this.bgpictrue= `url(data:image/jpeg;base64,${event.message.picture})`


”但是报错了 sanitizing unsafe style value SafeValue must use [property]=binding: , 才发现是Ionic2和TypeScript中对外部url资源链接做了安全限制,官网文档中对此做了解释: 
http://http://g.co/ng/security#xss
下面是最后的解决方案

import { DomSanitizer } from '@angular/platform-browser';

this.bgpictrue = this.sanitizer.bypassSecurityTrustStyle(`url(data:image/jpeg;base64,${event.message.picture})`);;

























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值