Change style of pseudo elements in angular2

2019-01-22 20:57发布

Is it possible to change style of pseudo elements using [style] or [ngStyle] in angular2?

in order to get a blur effect on a div acts like an overlay, and I should set up background-image on pseudo element.

I tried something like

<div class="blur" [style.before.backgroundImage]="'url('+ featuredImage[i] + ' )'">

it didn't work. I also tried this

<div class="blur" [ngStyle]="'{:before{ background-image:url('+ featuredImage[i] + ' )}}'">

2条回答
男人必须洒脱
2楼-- · 2019-01-22 21:02

You can achieve what you need with CSS variables.

In your style sheet you can set the background image like this:

.featured-image:after      { content: '';
                             background-image: var(--featured-image); }

After that you can programatically set this variable on the same element or on one higher up the DOM tree:

<div class="featured-image" [ngStyle]="{'--featured-image': featuredImage}">

More about CSS variables here: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables Note that the browser support is not complete yet.

Also note that you will needs to sanitize the url/style using sanitizer.bypassSecurityTrustResourceUrl(path) or sanitizer.bypassSecurityTrustStyle('--featured-image:url(' + path + ')')):

查看更多
爷、活的狠高调
3楼-- · 2019-01-22 21:13

No it's not possible. It is actually not an Angular issue: pseudo elements are not part of DOM tree, and because of that do not expose any DOM API that can be used to interact with them.

Usual approach if you want to deal with pseudo elements programmatically is indirect: you add/remove/change class and in CSS make this class affect corresponding pseudo-element. So in your case you could have one more class that changes necessary style:

.blur:before {/* some styles */}
.blur.background:before {/* set background */}

Now all you need to do is to toggle .background class on the element when you need before pseudo-element to get a background. You can use NgClass, for example.

查看更多
登录 后发表回答