codeandcloud
codeandcloud

Reputation: 55200

Custom attribute binding in HTML

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

Upvotes: 21

Views: 21956

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222522

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

<p [attr.data-target]="'collapse' + id">

Upvotes: 3

yurzui
yurzui

Reputation: 214007

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

Upvotes: 42

Related Questions