0

For example, if I have this structure:

<parent-component>
    <child-a class="a"></child-a>
    <child-a class="b selected"></child-a>
    <child-b class="c"></child-b>
    <child-b class="d"></child-b>
    ...
</parent-component>

How do I access the instance of ChildA with class ".selected" in my ParentComponent?

EDIT: In ParentComponent I have a list of 10 objects (in property items), and in its template I loop over the items array, and create ChildA or ChildB component for every item (whether ChildA or ChildB depends on some config in item).

Then by clicking on any item I mark it as 'selected' (the corresponding object in the items is stored as selectedItem). Later I need to access the component, that corresponds to the selectedItem (and has ".selected" class").

3
  • It's unclear what you asking. Create a plunk and clarify your specific problem. Commented Feb 9, 2017 at 15:04
  • Don't think you can select a child component by it's class without just querying the dom. You could give it a name and use @ContentChild to select it. e.g. <child-component-a #childB class="b"></child-component-a> Commented Feb 9, 2017 at 15:07
  • @RomanC updated question with some more info. Commented Feb 9, 2017 at 15:38

1 Answer 1

3

use @ContentChild or @ContentChildren in your parent.

For example: In your case use: @ContentChildren(ChildComponentA) childs: QueryList<ChildComponentA>; and u got all childs now just simple iterate.

For more information go here: https://angular.io/docs/ts/latest/api/core/index/ContentChildren-decorator.html


EDIT: You can use ElementRef in child to detect selected class, here you are an example:

plunkr here it is this what do u want to do ??

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

3 Comments

and what about the ".selected" class?
the best way (for now and for me) is add property to child-N, isSelected, and check it when iterate trought component query list
@eagor i update my answer, i add solution using ElementRef it help you ?

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.