1

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?

3
  • Can you share your child component code? Commented Jan 23, 2020 at 1:58
  • 1
    Yes. It is possible Commented Jan 23, 2020 at 2:04
  • 1
    It is possible. you need to dynamically set the checkboxes based on the Input decorator. Let's say on your child you have an @Input checkBoxId:String='1'. On checkboxes <checkbox [id]="checkBoxId"+ i> Commented Jan 23, 2020 at 2:19

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

I know, but it doesn't and it won't.

Your Answer

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.