How to add background-image using ngStyle (angular2)?

How to use ngStyle to add background-image? My code doesn't work:

this.photo = 'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg';

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

Solution 1:

I think you could try this:

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

From reading your ngStyle expression, I guess that you missed some "'"...

Solution 2:

Also you can try this:

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

Solution 3:

import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

  constructor(private sanitizer:DomSanitizer) {
    this.name = 'Angular!'
    this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(http://www.freephotos.se/images/photos_medium/white-flower-4.jpg)');
  }
<div [style.background-image]="backgroundImg"></div>

See also

  • https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
  • In RC.1 some styles can't be added using binding syntax
  • Plunker example

Solution 4:

Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.

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 {

  public backgroundImg: SafeStyle;
  @Input() myObject: any;

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {
     this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');
  }

}
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>

Solution 5:

Use Instead

[ngStyle]="{'background-image':' url(' + instagram?.image + ')'}"