Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update CSS variable in Angular

Tags:

css

angular

I want to use in my Angular app Bennett Feely "Image-effects".

For exemple this is the 'photo-border-effect':

.photo-border-effect {
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Point_Reyes_Lighthouse_%28April_2012%29.jpg/593px-Point_Reyes_Lighthouse_%28April_2012%29.jpg), url(https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Point_Reyes_Lighthouse_%28April_2012%29.jpg/593px-Point_Reyes_Lighthouse_%28April_2012%29.jpg);
  background-position: center;
  background-size: 60%, 20%;
  background-repeat: no-repeat, repeat;
}

[class$=-effect] img {
    vertical-align: top !important;
    margin: 0 !important;
    opacity: 0 !important;
}

/* CodePen Styles */
body {
    display: flex;
    height: 100vh;
}
div {
    margin: auto;
}
<div class="photo-border-effect">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Point_Reyes_Lighthouse_%28April_2012%29.jpg/593px-Point_Reyes_Lighthouse_%28April_2012%29.jpg">
</div>

But I have to change the urls in the CSS manually, not very convenient for my app. I know I can use CSS variables but I can't find a way to update it from my .ts directly.

What is the proper way to update CSS variable in Angular?

Mihir Dave response could work but I have cases with different background-image in the same class:

.flannel-effect {
  background-image: url(photo.jpg);
  background-size: cover;
  background-position: center;
}

@supports (background-blend-mode: overlay) {
  .flannel-effect {
    background-image: url(photo.jpg), url(photo.jpg), url(photo.jpg);
    background-position: center;
    background-size: 100%, 100000% 100%, 100% 100000%;
    background-blend-mode: overlay;
  }
}
like image 256
Toto Briac Avatar asked Nov 24 '25 11:11

Toto Briac


1 Answers

I found a quick and easy way to do it.

I use CSS variables and set the value from my .ts using DomSanitizer.

Here is a Stackblitz with this solution implemented.

like image 108
Toto Briac Avatar answered Nov 26 '25 03:11

Toto Briac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!