Petya Naumova
Petya Naumova

Reputation: 717

How to access a child element that is located inside ng-template by its id in a parent component?

this is pretty straightforward and I could not find any solution that works for me, including reading the Angular documentation.

So, I want to access a child component from its parent by the child's id because I want to use it in Jasmine unit test for the parent component.

The problem is that the child component is inside ng-template.

And I don't have a reference to it. I tried different solutions, none of them work.

This is an example code:
This ng-template is located in the parent component:

<ng-template #templateName>
   <child-component id="child-component"></child-component>
</ng-template>

And in the parent component:

@ViewChild('templateName') template;

How to access the <child-component> </child-component> by its id by the parent?

Any help would bre greatly appreciated!
Thank you!

Upvotes: 0

Views: 820

Answers (1)

Yozmo
Yozmo

Reputation: 581

You can use something like:

fixture.debugElement.query(By.css('#yourId').nativeElement;

Or you have as well:

fixture.debugElement.query(By.directive(YourComponent)).nativeElement;

Upvotes: 1

Related Questions