【问题标题】:NgStyle with dynamic content proper syntax angular 4/2具有动态内容的 NgStyle 正确的语法 angular 4/2
【发布时间】:2018-07-18 10:21:45
【问题描述】:

我正在使用 NgStyle 以 4 角动态设置容器的背景图像。

这个网站:说正确的语法如下

[ngStyle]="{'background-image': venueobject.groupphoto[0]}">

[ngStyle]="{'background-image': 'venueobject.groupphoto[0]'}">

我还看到把整个东西变成一个字符串:

[ngStyle]="'background-image': 'url(' + 'venueobject.groupphoto[0]'+ ')'">

[ngStyle]="'background-image: url(' + venueobject.groupphoto[0] + ')'">

但我一直没有得到它。页面正在呈现,所以我的 html 没有损坏,但图像没有显示。

这目前不适合,我正在努力让它变得适合。

请帮我搞定

拥抱和亲吻

【问题讨论】:

    标签: html angular typescript ng-style


    【解决方案1】:

    您可以尝试以下方法:

    在你的 ts 文件中:

    import { DomSanitizer } from '@angular/platform-browser';
    
    constructor(private sanitizer: DomSanitizer) { }
    
    getBackgroundImg() {
        // replace the path to your image here
        const img = 'assets/img/wall.png';
        const style = `background-image: url(${img})`;
        // this is to bypass this warning 'WARNING: sanitizing unsafe style value background-image: url(assets/img/wall.png) (see http://g.co/ng/security#xss)'
        return this.sanitizer.bypassSecurityTrustStyle(style);
    }
    

    在您的 html 文件中:

    <div [style]="getBackgroundImg()"></div>
    

    您还需要设置 div 的宽度和高度才能看到图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2016-07-14
      • 1970-01-01
      相关资源
      最近更新 更多