21

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

asked Feb 10, 2018 at 5:23
0

2 Answers 2

42

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

answered Feb 10, 2018 at 5:51
Sign up to request clarification or add additional context in comments.

Comments

3

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

<p [attr.data-target]="'collapse' + id">
Arun Kumaresh
6,2966 gold badges38 silver badges50 bronze badges
answered Feb 10, 2018 at 5:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.