Dynamically populate css pseudo-element "with" with Angular2 content

It's not easy for me to try to dynamically populate the content value for the :before pseudo-element. I found out that this is possible in earlier versions of AngularJS in another question above here , creating an additional data attribute for the element with before -pseudo on it, and then read that value using attr() in CSS.

It seems to work just fine when using a simple 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 populate data-before with such interpolation, I get an error message:

 // CSS .test:before { content: attr(data-before); } // Template <div class="test" data-before="{{name}}"> <h2>Hello {{name}}</h2> </div> 

What am I missing here? Error Created:

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

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

+6
source share
1 answer

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

UPDATE

You can also just omit the square brackets around name as follows:

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

This is similar to the agreement in a number of examples that I see. This works, I think, because you are already telling Angular to bind by specifying [attr.data-before] , and it is assumed that the data on the right comes from the corresponding component.

+6
source

Source: https://habr.com/ru/post/1014074/


All Articles