0

In my Angular project, I have a div with a background image. When I hover over it, a new class gets added.

Right, when I hover over it, I want to set the opacity of the background image.

I have looked for answers here

Can I set an opacity only to the background image of a div?

but those solutions require that I know the url. Since my url is dynamic and is individual for every component, I have to do it in the template.

enter image description here

Or in code format:

[style.background-image]="
  linear-gradient(
rgba(255, 255, 255, 0.5),
rgba(255, 255, 255, 0.5)
), url( + thumbnailPathGenerator() + )
"

I am trying to use the first solution from the link in my template. It may be not the prettiest way to do it, but this is the only solution I can think of. I tried setting the commas correctly, but I am doing that incorrectly always.

How to write those multiple css commands in the style.background-image without getting the error marks?

IonicMan
  • 743
  • 1
  • 12
  • 31
  • 1
    Have you tried writing it `linearGradient`. Pretty sure when you’re setting styles using the template binding method you need to write the style property as you would with js. Meaning any multi word css property becomes camel cased. – Levidps Dec 12 '22 at 11:00

1 Answers1

0

Define a getter in your component ts file and pass it as value like

[style.background-image]="backgroundImage"

in your component ts file

get backgroundImage(): string {
    return `url(${this.thumbnailPathGenerator()})`;
}

or

get backgroundImage(): string {
    return 'url(' + this.thumbnailPathGenerator() + ')';
}

Or wrap your css value in single quotes '' like :

[style.background-image]=" 'url(' + thumbnailPathGenerator() + ')'"

Try to avoid calling functions to get style values, since this function is called each time angular change detection is triggered.

Mehyar Sawas
  • 1,187
  • 6
  • 15