Using Angular 5, I bind data-target as [attr.data-target]="id"
JavaScript Object
var ids = [1, 2];
HTML
<div *ngFor="let id in ids">
<p [attr.data-target]="id"></p>
</div>
which gets rendered as
<div>
<p data-target="1"></p>
<p data-target="2"></p>
</div>
The aim is achieve something like
<div>
<p data-target="collapse1"></p>
<p data-target="collapse2"></p>
</div>
How to prepend/append some static string
to attributes (date-, aria)?
If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.
Attribute binding is used to bind an attribute property of a view element. Attribute binding is mainly useful where we don't have any property view with respect to an HTML element attribute. Let's consider an example where we are trying to bind a value to the colspan property of the element.
Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
There are several ways to accomplish this:
Interpolation
attr.data-target="collapse{{id}}"
Attribute binding
[attr.data-target]="'collapse' + id"
Attribute binding canonical form
bind-attr.data-target="'collapse' + id"
Using custom method
ts
getTarget(id) {
return `collapse${id}`;
}
html
[attr.data-target]="getTarget(id)"
or
bind-attr.data-target="getTarget(id)"
Live example on ng-run
It works the same way you append with two way binding variable, in this case
<p [attr.data-target]="'collapse' + id">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With