151

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>
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Ignat
  • 3,727
  • 6
  • 16
  • 17

9 Answers9

297

I think you could try this:

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

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

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Tested. Working with RC.1. It should't be needed for RC.2 and newer releases according to what they say [here](http://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax) – Lucio Mollinedo Jun 27 '16 at 22:06
  • 8
    I prefer `this.photo = \`url(${photo})\`;` `[style.background-image]='photo'`. – Lin Du Aug 16 '17 at 06:41
  • 5
    Bear in mind that spaces in picture URL (picture name) may cause a silent `[ngStyle]` and `[style.background-image]` rendering failure. – vter Mar 22 '18 at 19:31
  • This is good. I once used it and it works well. Good one – BeardedPrince Feb 16 '21 at 21:46
101

Also you can try this:

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

Todmy
  • 1,051
  • 1
  • 8
  • 12
  • 4
    @redfox05 I suppose ngStyle is a syntactic sugar. The main difference is that ngStyle allows you to apply several css rules, but [style.] allows only one. The next are equivalent: `
    First
    ` and `
    Second
    `
    – Todmy Dec 09 '16 at 10:34
  • I've used this [style.css] approach, though I can't get [style.background-repeat] to work, you know why? – Anders Metnik Jan 27 '17 at 13:06
  • How to do conditional styling using this approach? Let's say if I want to check if photo is not null and then only apply this style? – Pankaj Jan 09 '20 at 21:57
34
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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
9

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>
Uliana Pavelko
  • 2,824
  • 28
  • 32
7

Use Instead

[ngStyle]="{'background-image':' url(' + instagram?.image + ')'}"
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Vijay Chauhan
  • 1,282
  • 19
  • 18
6

My background image wasn't working because the URL had a space in it and thus I needed to URL encode it.

You can check if this is the issue you're having by trying a different image URL that doesn't have characters that need escaping.

You could do this to the data in the component just using Javascripts built in encodeURI() method.

Personally I wanted to create a pipe for it so that it could be used in the template.

To do this you can create a very simple pipe. For example:

src/app/pipes/encode-uri.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'encodeUri'
})
export class EncodeUriPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return encodeURI(value);
  }
}

src/app/app.module.ts

import { EncodeUriPipe } from './pipes/encode-uri.pipe';
...

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule
    ...
  ],
  exports: [
    ...
  ],
 declarations: [
    AppComponent,
    EncodeUriPipe
 ],
 bootstrap: [ AppComponent ]
})

export class AppModule { }

src/app/app.component.ts

import {Component} from '@angular/core';

@Component({
  // tslint:disable-next-line
  selector: 'body',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {
  myUrlVariable: string;
  constructor() {
    this.myUrlVariable = 'http://myimagewith space init.com';
  }
}

src/app/app.component.html

<div [style.background-image]="'url(' + (myUrlVariable | encodeUri) + ')'" ></div>
Tom Benyon
  • 971
  • 10
  • 15
4

You can use 2 methods:

Method 1

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

Method 2

<div [style.background-image]="'url(&quot;' + photo + '&quot;)'"></div>

Note: it is important to surround the URL with " char.

riofly
  • 1,694
  • 3
  • 19
  • 40
4

Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.

.bg-img {                \/          \/
    background-image: url('http://...');
}

To do so escape quot character in HTML via \'

                                          \/                                  \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>
simply good
  • 991
  • 1
  • 12
  • 26
3

My solution, using if..else statement. It is always a good practice if you want to avoid unnecessary frustrations, to check that your variable exists and is set. Otherwise, provide a backup image in case; You can also specify multiple style properties, like background-position: center, etc.

<div [ngStyle]="{'background-image': this.photo ? 'url(' + this.photo + ')' : 'https://placehold.it/70x70', 'background-position': 'center' }"></div>
AllJs
  • 1,760
  • 4
  • 27
  • 48