I updated a bit your code in order to work:
@Component({
selector: 'my-app',
template: `
<div [style.background-image]="profileImage" style="width: 961px; height: 688px;"></div>
<h2> {{message}}</h2>
`,
})
export class App {
profileImage: string;
message: string;
constructor(private sanitizer: DomSanitizer) {
this.message = "Before async";
}
async ngOnInit() {
await delay(2000);
this.message = "Updating Photo";
const url = 'https://4.bp.blogspot.com/--RBVfn6FzOI/Tq5kOxFGKEI/AAAAAAAACnM/LaiZLD0sUKY/s1600/cats.jpg';
this.profileImage = this.sanitizer.bypassSecurityTrustStyle(`url(${url})`);
}
}
Changes
1st: Change:
constructor(sanitizer: DomSanitizer)
into this:
constructor(private sanitizer: DomSanitizer)
Thus having the sanitizer
as a member of the class in order to be accessible in ngOnInit()
.
2nd: Set the dimension of the <div>
. This will not adjust automatically to your background image size. So I set width
and height
. Other solutions exist, like using the aspect ratio of the image, or keeping an invisible <img>
. These and more are described in this answer.
3nd: Set the image HTTP scheme from http
to https
because you are receiving a warning in Plunker which serves content over https
.
Updated Plunk