vester
vester

Reputation: 455

Give dynamic ID to Angular template html

I have created a html template that is reused a couple times in a parent component but with different data passed on.

I have parent.component.html which has

    <child-component title="one"></child-component>
    <child-component title="two"></child-component>
    <child-component title="three"></child-component>

Which works just fine.

The thing is, in 'child-component' I have checkboxes and their corresponding labels. As you know, they need the for attribute to know when a checkbox is checked. As I have realized, Angular re-renders the child-component each time is called, like a clone, and the for attributes are all the same for each child-component, so checkboxes don't work. I want to be able to create dynamic for and id for each checkbox each time the child-component is called upon.

I tried to explain my problem as best as I could. Is such solution possible?

Upvotes: 1

Views: 1761

Answers (1)

vester
vester

Reputation: 455

Inspired by @mynameisx comment, the solution was simpler than I thought.

As I have the title property passed on with a different value, that itself differentiates each child component. So in each child component, I wrote this for the id and for of the input:

<input type="checkbox" id="{{ title }} + Check">
<label for="{{ title }} + Check"></label>

The checkboxes work!

Upvotes: 1

Related Questions