Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
}
like image 506
Kevin Quiring Avatar asked Sep 05 '17 23:09

Kevin Quiring


People also ask

How does Angular do data binding?

Angular data binding is a two-way process: it can both send and receive data. This means that when you change something in your view, the model updates automatically, and vice versa. The ngModel directive makes this two-way data binding possible.

Does Angular have data binding?

Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.

How many ways we can bind data in Angular?

AngularJS provides two types of Data Binding: One-way data binding. Two-way data binding.

What is one-way data binding in Angular?

One-way data binding in Angular (i.e. unidirectional binding) is a way to bind data from the component to the view (DOM) or vice versa - from view to the component. It is used to display information to the end-user which automatically stays synchronized with each change of the underlying data.


1 Answers

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}}">
like image 50
Dai Avatar answered Oct 25 '22 19:10

Dai