Kevin Quiring
Kevin Quiring

Reputation: 649

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

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

Upvotes: 10

Views: 9790

Answers (1)

Dai
Dai

Reputation: 155578

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

Upvotes: 26

Related Questions