【问题标题】:Angular 2 ngStyle and background-image [duplicate]Angular 2 ngStyle 和背景图像 [重复]
【发布时间】:2018-02-12 22:29:39
【问题描述】:

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

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

【问题讨论】:

标签: css angular angular-directive


【解决方案1】:

收到的 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);
  }

【讨论】:

  • 抱歉,不工作
猜你喜欢
  • 2018-10-12
  • 2017-08-30
  • 1970-01-01
  • 2016-09-26
  • 2020-06-24
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
相关资源
最近更新 更多