Angular 2 ngStyle 和背景图像

Angular 2 ngStyle and background-image

我在使用 Angular 2 ngStyle 指令时遇到了很大的麻烦。我无法从 base64 编码文件设置背景图像。现在 template.html 我有这个:

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

其中 'images' 是一组 base64 编码的 .png 文件及其名称。

Console.log of images[3].file 给我这个(麻烦不在图像内部,当我在 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);
  }