Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically fill css Pseudo-element 'before' content with Angular2

Tags:

html

css

angular

I'm having a hard time trying to dynamically fill the 'content'-value on a :before pseudo-element. I've found out it was possible on earlier versions of AngularJS in another question over here, by creating an extra data attribute on the element that has the before-pseudo element on it, and then read that value using attr() in CSS.

It seems to work just fine when using a plain string as a value:

// CSS
.test:before {
  content: attr(data-before);
}

// Template
<div class="test" data-before="before text goes here">
  <h2>Hello {{name}}</h2>
</div>

But when I try to fill the data-before with interpolation like this, I get an error:

// CSS
.test:before {
  content: attr(data-before);
}

// Template
<div class="test" data-before="{{name}}">
  <h2>Hello {{name}}</h2>
</div>

What am I missing here? The error generated is:

Error: Template parse errors:
Can't bind to 'before' since it isn't a known property of 'div'.

Here's the non-working version in plunker: http://plnkr.co/edit/HwVp9jlsx6uKfoRduxWu

like image 833
Creatyfus Avatar asked Jan 14 '17 00:01

Creatyfus


2 Answers

Use: <div class="test" [attr.data-before]="[name]">

UPDATE

You can also just drop the square brackets around name like this:

<div ... [attr.data-before]="name">.

This appears to be the convention in a number of examples I see. This works, I think, because you are already telling Angular to perform binding by specifying the [attr.data-before], and it assumes the data on the right is coming from the corresponding component.

like image 186
Frank Fajardo Avatar answered Nov 03 '22 07:11

Frank Fajardo


For me, the below one worked in Angular version 8.

HTML:

<div style="display: block" class="testcl" [attr.data-before-content]="dynamicContent"></div>

CSS:

.testcl::before{
/* content: "56%"; */
content: attr(data-before-content);
position: absolute;
left: 46%;
top: 50%;
font-weight: 700;
font-size: 24px;
color: #55b358;

}

like image 23
sibi Avatar answered Nov 03 '22 09:11

sibi