问题描述
我在使用 Angular 2 ngStyle 指令时遇到了大麻烦.我无法从 base64 编码文件设置背景图像.现在在 template.html 我有这个:
其中图像"是 base64 编码的 .png 文件及其名称的数组.
图像[3].file 的控制台.log 给了我这个(问题不在图像内部,当我在 img src='...' 中使用它时它工作得很好):
有什么想法吗?非常感谢您的回答!:)
解决方案 收到的 base64 图像中的换行符是一个问题的原因.这是我的解决方案:
//这去模板:[style.background-image]="makeTrustedImage(images[i].file)"//这去组件:构造函数(私有 domSanitizer:DomSanitizer){}makeTrustedImage(项目){const imageString = JSON.stringify(item).replace(/\\n/g, '');const style = 'url(' + imageString + ')';返回 this.domSanitizer.bypassSecurityTrustStyle(style);}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! :)
解决方案 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);
}
这篇关于Angular 2 ngStyle 和背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-15 16:23