[javascript] 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>

This question is related to javascript html css angular

The answer is


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>

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>

Use Instead

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

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


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.

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


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.


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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7