Sometimes, we want to add background-image using ngStyle with Angular and TypeScript.,.
In this article, we’ll loopk at how to add background-image using ngStyle with Angular and TypeScript.
How to add background-image using ngStyle with Angular and TypeScript?
To add background-image using ngStyle with Angular and TypeScript, we set the [style.background-image]
attribute.
For instance, we write
<div
*ngIf="backgroundImg.length > 0"
[style.background-image]="backgroundImg"
></div>
in the template to set the background image to backgroundImg
.
Then we write
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 + ")"
);
}
}
in the component to set backgroundImg
to a URL string.
We stop the string from being escaped with bypassSecurityTrustStyle
.
Conclusion
To add background-image using ngStyle with Angular and TypeScript, we set the [style.background-image]
attribute.