Angular 2 ngStyle 和背景图像[重复]

2024-03-14

我对 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='...' 中使用它时它工作得很好):

有任何想法吗?非常感谢各位的解答! :)


收到的 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);
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2 ngStyle 和背景图像[重复] 的相关文章

随机推荐