如何使用ngStyle(angular2)添加背景图片?

如何使用ngStyle添加背景图片? 我的代码不起作用:

this.photo = 'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg'; <div [ngStyle]="{'background-image': url(' + photo + ')}"></div> 

我想你可以试试这个:

 <div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div> 

从阅读你的ngStyleexpression式,我猜你错过了一些“'”…

你也可以试试这个:

[style.background-image]="'url(' + photo + ')'"

 import {BrowserModule, DomSanitizer} from '@angular/platform-browser' constructor(private sanitizer:DomSanitizer) { this.name = 'Angular!' this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(http://www.freephotos.sehttp://img.dovov.comphotos_medium/white-flower-4.jpg)'); } 
 <div [style.background-image]="backgroundImg"></div> 

也可以看看

看起来像你的风格已被消毒,绕过它尝试使用DomSanitizer的bypassSecurityTrustStyle方法。

 import { Component, OnInit, Input } from '@angular/core'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; @Component({ selector: 'my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.scss'] }) export class MyComponent implements OnInit { private backgroundImg: SafeStyle; @Input() myObject: any; constructor(private sanitizer: DomSanitizer) {} ngOnInit() { this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')'); } } 
 <div [style.background-image]="backgroundImg"></div>