Angular2中的ngStyle和background-image

3

我有一个关于Angular 2 ngStyle指令的大问题。我无法从base64编码文件中设置背景图片。现在在template.html中我有以下内容:

  <div class="projects_item_wrap" [ngStyle]="{'background-image':'url('+images[i].file+')'}">

'images'是一个包含base64编码的.png文件及其名称的数组。

当我使用images[3].file的console.log时,它给了我这个(问题不在图片内,在img src='...'中使用时它能够完美工作):

blob image

有什么想法吗?非常感谢您的回答!:)


请参见 https://dev59.com/SVoU5IYBdhLWcg3wzZPw#37076868。 - Günter Zöchbauer
如果你指的是domSanitizer - 我已经尝试过了 - 没有任何改变 :( - Wondergrauf
替代方案 [style.background-image]="'url('+images[i].file+')' | safeResourceUrl" (其中管道使用 bypassSecurityTrustResourceUrl(value))。 - Günter Zöchbauer
请参见 https://dev59.com/SJrga4cB1Zd3GeqPsM78 - Günter Zöchbauer
尝试添加管道-没有结果。也尝试添加sanitizer.bypassSecurityTrustStyle()-同样,没有结果。 - Wondergrauf
显示剩余7条评论
1个回答

2

接收到的Base64图像中的换行符是问题的原因。这是我的解决方案:

//This goes to template <div>:
[style.background-image]="makeTrustedImage(images[i].file)"

//And this goes to component:
constructor(private domSanitizer: DomSanitizer) {}

makeTrustedImage(item) {
    const imageString =  JSON.stringify(item).replace(/\\n/g, '');
    const style = 'url(' + imageString + ')';
    return this.domSanitizer.bypassSecurityTrustStyle(style);
  }

抱歉,无法工作。 - Pullat Junaid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接