Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom attribute binding in HTML

Tags:

angular

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

like image 275
naveen Avatar asked Feb 10 '18 05:02

naveen


People also ask

How do I create a custom attribute in HTML?

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.

How do you bind attributes?

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.

How do you set data attributes in HTML elements?

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.

What are data attributes in HTML?

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.


2 Answers

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

like image 79
yurzui Avatar answered Oct 10 '22 19:10

yurzui


It works the same way you append with two way binding variable, in this case

<p [attr.data-target]="'collapse' + id">
like image 39
Sajeetharan Avatar answered Oct 10 '22 19:10

Sajeetharan