3

I want to use a variable width in my angular 5 component template, just like this:

<style>
    input:checked + .slider:before {
        transform: translateX({{width}}px);
    }
</style>

While 'width' is a variable defined in component!

however the "{{width}}" is not parsed ,how to implement this function.thanks!

Icarus
  • 1,627
  • 7
  • 18
  • 32
Yang Rui
  • 241
  • 5
  • 11

1 Answers1

2

You can use Angular ngStyle in this case:

[ngStyle]="{ width: width }"

Take a look at this demo

Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61
  • Since OP asked for applying over CSS over pseudo element, it won't possible inline. Otherwise `ngStyle` is way to go. – Pankaj Parkar Jan 17 '18 at 07:15
  • @m98 thank you rapid response! in this case,the style selector is too complex ans not belong to a single element ,could you tell me how to write this in ngstyle. thanks! – Yang Rui Jan 17 '18 at 07:28
  • @YangRui You're welcome, unfortunately you cannot have pseudoelements within inline styling – Mohammad Kermani Jan 17 '18 at 08:10
  • @M98,no solution for this? – Yang Rui Jan 17 '18 at 08:16
  • No, there might be some solution, but since you're going to use `pseudo` (like `:before`), the ngStyle does not support it. You want when the input checked, the `slider:before` use `translateX` to move. Why don't you try to do it using (let's say) Angular Animation? – Mohammad Kermani Jan 17 '18 at 08:19
  • @M98,i am not very familiar with css and Angular Animation. i use this just want to have a interaction,This sniper is used in a switch input,which have a dynamic width. thanks! – Yang Rui Jan 17 '18 at 08:25
  • For Angular 7, I had to add `'` around the style, like: `[ngStyle]="{ 'stroke-width': width }" - although this was for an SVG. Maybe it applies for all styles. – Jeppe Feb 28 '19 at 21:45
  • how to use ngStyle for the host ? as it doesn't have an html tag – getName Aug 29 '21 at 17:13