How to bind to a data attribute using Angular 2+?

天涯浪子 提交于 2019-12-12 13:38:03

问题


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">

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;
  }
}

回答1:


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).

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">

Or:

<td attr.data-title="{{object.someString}}">


来源:https://stackoverflow.com/questions/46064873/how-to-bind-to-a-data-attribute-using-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!