Your code has been modified to ensure functionality:
@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})`);
}
}
Adjustments Made:
1st Modification: Adjusted the constructor from:
constructor(sanitizer: DomSanitizer)
to:
constructor(private sanitizer: DomSanitizer)
This change makes the sanitizer
accessible within the class for use in ngOnInit()
.
2nd Change: Fixed the dimensions of the <div>
. By specifying width
and height
, the size is set manually to prevent automatic adjustment based on the background image size. Different solutions, like maintaining aspect ratio or utilizing an invisible <img>
, are detailed in this resource.
3rd Update: Adjusted the image HTTP scheme from http
to https
to resolve a warning in Plunker related to serving content over https
.
View Updated Plunk