Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Which of the following is the correct syntax to set background image?

The most common & simple way to add background image is using the background image attribute inside the <body> tag.


I think you could try this:

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

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


Also you can try this:

[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.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

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>