1

I want to change the 'content' property of a CSS class which is getting applied on Slide-Toggle of angular.

this is my SCSS -

:host .red {
  .mat-toggle {
    ::ng-deep .mat-slide-toggle-bar{
      &::after{
        content: attr(data-active);;
      }
    }
  }
}

This is how I pass attrs -

<div class="red"
attr.data-active="activeData">
    <mat-toggle></mat-toggle>
</div>

If I hard-code the value in CSS then it's working properly, but unable to bind the string dynamically.

Please help.

Prafull Dhadkar
  • 891
  • 2
  • 10
  • 23

1 Answers1

0

The issue is that attr() will not pierce down to the child element to set a value... it only works on selected element.

Reference to MDN that specifies selected element in the description.

MDN

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

With this in mind, you would need to set the attribute value into a CSS variable for later use.


Using the following approach from this SO answer may be a viable workaround.

Add label-attr to be used in CSS via attribute selector, then set custom property/CSS variable via style="--myLabel:'activeLabel';"

<div class="red">
    <mat-slide-toggle style="--myLabel:'activeLabel';" label-attr>
    </mat-slide-toggle>
</div>

In CSS use the attribute selector to get a reference to your CSS variable and set it to content via content: var(--myLabel).

::ng-deep mat-slide-toggle[label-attr] ::ng-deep .mat-slide-toggle-bar:after {
  content: var(--myLabel);
}

STACKBLITZ

https://stackblitz.com/edit/angular-azgink-dvthvu?file=src/app/slide-toggle-configurable-example.css

Marshal
  • 10,499
  • 2
  • 34
  • 53