如何使用 Angular 2+ 绑定到数据属性? [英] How to bind to a data attribute using Angular 2+?
问题描述
我使用的数据表主要是用我在网上找到的 css 创建的.在其中一列中有一个 css 数据属性data-title",它被分配了一个字符串.
I am using a data table created mostly with css that I found online. In one of the columns there is a css data attribute "data-title" which is assigned a string.
<td data-title="someString">
当我输入一个字符串时,列内的样式按预期工作.当我尝试绑定到对象字符串时,绑定不会像我预期的那样工作.我试过了
When I enter a string, the styling inside the column works as expected. When I try to bind to an objects string, the binding doesn't work like I would expect. I tried
<td data-title="object.someString">
它只显示文字object.someString",我试过
which just displays literal 'object.someString' and I tried
<td data-title="{{object.someString}}">
什么都不显示(空白).知道为什么我的绑定在这里不起作用吗?
which displays nothing (blank). Any idea why my binding isn't working here?
CSS:
.responsive-table tbody td[data-title]:before {
content: attr(data-title);
float: left;
font-size: .9em;
color: #565248;
}
@media (min-width: 48em) {
.responsive-table tbody td[data-title]:before {
content: none;
}
}
推荐答案
Angular 2 不会使用更简单的 {{ }}
语法绑定到 data-
属性,因为它尝试将它们映射到 DOM 属性,并且没有 data-title
的 DOM 属性(而且 Angular2 似乎还不够智能,无法使用 dataset
还 -除非我遗漏了什么).
Angular 2 doesn't bind to data-
attributes using the simpler {{ }}
syntax because it tries to map them to DOM properties, and there isn't a DOM property for data-title
(and it seems Angular2 isn't smart enough to use dataset
yet - unless I'm missing something).
因此要绑定到 data-
属性,您需要使用 attr.data-title={{}}
或 [attr.data-...]=""
语法.请参阅此 QA:Angular 2 数据属性
So to bind to data-
attributes you need to use the attr.data-title={{}}
or [attr.data-...]=""
syntax. See this QA: Angular 2 data attributes
<td [attr.data-title]="object.someString">
或者:
<td attr.data-title="{{object.someString}}">
这篇关于如何使用 Angular 2+ 绑定到数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!