2017-05-04 46 views
0

模板:角4 CSS DIV的背景图像结合不起作用

<div [style.background-image]="profileImage" ></div> 

TS:

private profileImage: any; 
private sanitizer:DomSanitizer 

从服务中获得的照片:

this.profileImage = this.sanitizer.bypassSecurityTrustStyle("url("+ data.photo + ")"); 

结合不工作。我检查了Chrome开发工具,未下载照片。当刷新页面时,它工作正常,但它必须在值设置为服务时工作。用ngStyle也试过,它不起作用。

Plunkr链接https://plnkr.co/edit/IhVGjiImyfk0F1u6cWtG?p=preview

+1

我不明白如何刷新使它的工作?它仍然在示例过程中。你能展示更多的代码和项目结构吗? – wannadream

+0

在这个plunkr中工作正常https://plnkr.co/edit/jKMDoSEc8pq9BnhljiCw?p=preview –

+0

plunkr正在为简单的情况工作,但是当从服务中检索数据时它不是 – jaks

回答

1

我为了更新了一下你的代码工作:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div [style.background-image]="profileImage" style="width: 961px; height: 688px;"></div> 
    <h2> {{message}}</h2> 
    `, 
}) 
export class App { 

    profileImage: string; 
    message: string; 

    constructor(private sanitizer: DomSanitizer) { 
    this.message = "Before async"; 
    } 

    async ngOnInit() { 
    await delay(2000); 
    this.message = "Updating Photo"; 
    const url = 'https://4.bp.blogspot.com/--RBVfn6FzOI/Tq5kOxFGKEI/AAAAAAAACnM/LaiZLD0sUKY/s1600/cats.jpg'; 
    this.profileImage = this.sanitizer.bypassSecurityTrustStyle(`url(${url})`); 
    } 
} 

变化

1:变化:

constructor(sanitizer: DomSanitizer)

成这样:

constructor(private sanitizer: DomSanitizer)

因此具有sanitizer作为类的一个成员,以便在ngOnInit()访问。

2nd:设置<div>的尺寸。这不会自动调整为您的背景图像大小。所以我设置了widthheight。还有其他解决方案,例如使用图像的宽高比,或者保留不可见的<img>。这些和更多描述在this answer

3ND:因为你接收Plunker警告其在https服务内容设置图像HTTP方案从httphttps

Updated Plunk

+0

用引号也不起作用。检查以上plunkr链接 – jaks

+0

@jaks对不起,我以前的评论是愚蠢的 - 'url(...)|网址('...')| url(“...”)是等价的。我用一个工作版本更新了我的评论。 – andreim

+0

真正的问题来自HTTP服务,图像被设置。所以它没有更新。现在将代码放入ngZone中,并工作。 – jaks