本文介绍了将Angular 2变量绑定到CSS伪类内容:attr()表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较将Angular 2变量绑定 [innerText] / {{}} 与绑定变量作为伪类内容的渲染性能(因为上述方法强制元素重新呈现)

I wanted to compare performance of rendering Angular 2 variable binding [innerText]/{{}} with binding variable as content of pseudo-class(because methods above forces element re rendering)

但是,我在尝试使用CSS进行角度标记时很费劲.

However, I struggle trying to make angular markup work with css.

可行

CSS:

.my-el:after {
    content: attr(my-attr);
}

HTML

<div class="my-el" my-attr="text"></div>

但是将其更改为 my-attr ="{{myVar}}" 角度抛出错误:

But after change it to my-attr="{{myVar}}" Angular throws error:

browser_adapter.js:77 EXCEPTION: Template parse errors(...)

因此,我认为应该使用 attr.my-attr ="{{myVar}}"

So I red that I should use attr.my-attr="{{myVar}}"

但是将CSS更改为

.my-el:after {
    content: attr(attr.my-attr);
}

它不起作用(我猜点在这里不是有效的符号吗?).

it doesn't work (I guess dot isn't valid symbol here?).

我知道以上所有内容都没有多大意义,但是我发现它是一个有趣的问题,到目前为止我还无法解决.

I know that all above may have not much sense, however I'm finding it as interesting problem which I can't solve so far.

有什么想法可以使这两个一起工作吗?预先感谢!

Any ideas how to make these two work together? Thanks in advance!

推荐答案

您将必须通过以下方式绑定您的值

You will have to bind your value with the following way

<div class="my-el" [attr.my-attr]="myVar"></div>

这样,angular会将 myVar 内容附加到 my-attr 属性

This way angular will attach the myVar contents to the my-attr attribute

如果您需要在其前面加上 data-,请使用

If you need to prepend it with data- use

<div class="my-el" [attr.data-my-attr]="myVar"></div>

然后,您可以使用以下命令从CSS中访问值: attr(my-attr) attr(data-my-attr)

Then you can access the value from your css withattr(my-attr) or attr(data-my-attr)

这篇关于将Angular 2变量绑定到CSS伪类内容:attr()表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 00:56