简体   繁体   中英

attr binding is not working while using ::ng-deep on mat-toggle in angular

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM