Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Angular interpolated string in CSS content property

Tags:

html

css

angular

I am using the CSS content property content: attr(myValue); in an Angular 7 component's .css file

&::before {
    content: attr(myValue);
    position: absolute;
    left: 2em;
    font-weight: bold;
    top: 1em;
    display: block;
    font-family: 'Roboto', sans-serif;
    font-weight: 700;
    font-size: .785rem;
}

which is connected to a string value in the component's .html file like this:

      <div class="timeline-item" myValue='Can I use an interpolated value here instead?'>
        ...
      </div>

I want to insert an interpolated string value in the myValue in the .html. I have tried the various bind techniques outlined in the official Angular template syntax guide without any success.

Is there a way to insert the interpolated value in myValue? In other words, can I do the equivalent of this:

      <div class="timeline-item" myValue='{{myInterpolatedString}}'>
        ...
      </div>
like image 988
Winthorpe Avatar asked Jul 25 '26 07:07

Winthorpe


1 Answers

You cannot bind an unknown property like myValue on a div to a value, the runtime is giving you an error

Error: Template parse errors:
Can't bind to 'myValue' since it isn't a known property of 'div'. ("
<div class="timeline-item" [ERROR ->]myValue="{{'something'}}">
"): ng:///AppModule/AppComponent.html@4:31

You have to use attr.myValue instead. It is possible to use single quotes ' aswell as double-quotes ".

attr.myValue="{{myBoundValue}}"
attr.myValue='{{myBoundValue}}'

You could ommit the curly braces by using this syntax

[attr.myValue]="myBoundValue"
like image 118
Isitar Avatar answered Jul 27 '26 22:07

Isitar