简体   繁体   English

在 angular 的 mat-toggle 上使用 ::ng-deep 时,attr 绑定不起作用

[英]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.我想更改应用于 angular 的 Slide-Toggle 的 CSS 类的“内容”属性。

this is my SCSS -这是我的 SCSS -

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

This is how I pass attrs -这就是我通过 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.如果我在 CSS 中对值进行硬编码,则它可以正常工作,但无法动态绑定字符串。

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 .问题是attr()不会深入到子元素来设置值......它只适用于selected element

Reference to MDN that specifies selected element in the description.在描述中指定selected element MDN参考。

MDN MDN

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. attr() CSS 函数用于检索selected element的属性值并在样式表中使用它。 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.考虑到这一点,您需要将属性值设置为 CSS 变量以备后用。


Using the following approach from this SO answer may be a viable workaround.使用此 SO 答案中的以下方法可能是一种可行的解决方法。

Add label-attr to be used in CSS via attribute selector, then set custom property/CSS variable via style="--myLabel:'activeLabel';"通过属性选择器添加要在CSS使用的label-attr ,然后通过style="--myLabel:'activeLabel';"设置custom property/CSS variable

<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) .CSS使用属性选择器获取对 CSS 变量的引用,并通过content: var(--myLabel)将其设置为 content。

::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 https://stackblitz.com/edit/angular-azgink-dvthvu?file=src/app/slide-toggle-configurable-example.css

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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