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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With