angular4 的动态style之background-image

参考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 [style.color]="isSpecial ? 'red': 'green'">Red
 [style.background-color]="canSave ? 'cyan': 'grey'" >Save

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 [style.font-size.em]="isSpecial ? 3 : 1" >Big
 [style.font-size.%]="!isSpecial ? 150 : 50" >Small

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位的,怎么展示呢?

开始利用

,在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})`);;

























你可能感兴趣的:(javascript,angualr)