Angular 2 ngStyle and background-image [duplicate]

人走茶凉 提交于 2019-12-08 05:19:02

问题


I have a big trouble with Angular 2 ngStyle directive. I can't set background image from base64 encoded file. Now in template.html I have this:

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

Where 'images' is an array of base64 encoded .png files and their names.

Console.log of images[3].file give me this (trouble not inside an image, it works perfectly when I use it in img src='...'):

Any ideas? Thanks a lot for answers! :)


回答1:


Linebreaks within received base64 image was a reason of trouble. This is my solution:

//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);
  }


来源:https://stackoverflow.com/questions/46041210/angular-2-ngstyle-and-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!