RNdev
RNdev

Reputation: 1231

Angular: How can I pass a background image URL through HTML rather than CSS?

The Scenario:

I have an element in my Angular app that I want to add a background image to. At the moment I have this:

<div class={{background-class}}></div>

where background-class is, for example, "background-style-1", which is in my stylesheet like this:

background-style-1 {
  background-image: url(../../../../assets/images/contextmenu/person.png);
}

The element successfully displays the image, and if I query it, it shows this: enter image description here

The Problem:

I don't want to hard-code all the background image URLs into my stylesheet. Instead, I want to just pass the URL into the HTML tag.

What I've Tried

<div style="background-image: url(../../../../assets/images/contextmenu/person.png)"></div>

This fails to display the image, and when I query the element, it shows this:

enter image description here

What I Want To Know:

Why does passing the image URL as an inline style property not work, and how can I make it work?

Upvotes: 1

Views: 5189

Answers (4)

Mr.7
Mr.7

Reputation: 2713

You can either use [ngStyle] or [style.backgroundImage] to bind dynamic styles.

and it's better to pass image/icon name to the component.

[ngStyle]="{'background-image': 'url(path/to/icons' + iconName + ')'}"

or smililarly

[style.backgroundImage]= 'url(path/to/icons' + iconName + ')'

and the iconName would be

const iconName = 'logo.svg';

PS: Ensure that logo.svg is present in the given path.

Upvotes: 0

Adrita Sharma
Adrita Sharma

Reputation: 22213

You can use ngStyle:

HTML:

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

TS:

image = "assets/images/contextmenu/person.png"

Upvotes: 1

Passionate Coder
Passionate Coder

Reputation: 7294

You can use ngStyle directive to bind styles dynamically on html elements

In component set your path variable

path = '../../../../assets/images/contextmenu/person.png'

use it in template like below

<div [ngStyle]="{'background-image': 'url(' + path + ')'}"></div>

Try this

https://stackblitz.com/edit/angular-cxk5dr

Documention link for ngStyle

https://angular.io/api/common/NgStyle

Upvotes: 0

Nicolas
Nicolas

Reputation: 8650

You can dynamicaly set the background image from the html using this syntax : [style.someproperty]="'somevalue'". In your case, it can look something like this.

<div [style.backgroundImage]="'url(' + url + ')'"></div>

This will take the value of url ( defined in your controller) as the url for the background image.

Upvotes: 1

Related Questions