Reputation: 91
I would like to retrieve components within a ng-template
using @ContentChildren
.
See example here :
https://stackblitz.com/edit/github-ktnw8d-gaquer
My use case is the following : I have two generic panels, that must be displayed in every tab view I want to use. Those panels are wrapped into a component, which is called by various other components. For each component, I can add different panels after the generic ones. For that, I need the reference of the template (TemplateRef), and the reference of the component to get its values (a TabPanel)
In the console of the stackblitz, you can see that the variable tabPanels
contains two elements : the two TabPanel included in the AppComponent template, outside of the ng-template
. So, the descendants
property is working fine for those elements. But why doesn't it work with the panel injected inside ng-template
?
How can I achieve that ?
Upvotes: 2
Views: 8883
Reputation: 3062
But why doesn't it work with the panel injected inside ng-template ?
Because template / ng-template elements are not actually rendered to the DOM until they are explicitly injected or referenced from somewhere else. ContentChildren can't see anything inside that ng-template element because it interprets a bare ng-template tag basically the same as it would an HTML comment - there's nothing there for it to read.
If you want to do stuff to an ng-template element before its actually rendered/injected somewhere, you need to get the 'TemplateRef' of the element. There are a few ways to do this... I'm not familiar with PrimeNG and and I'm not entirely clear on what, specifically, you are trying to do (its not obvious from the demo code) so unfortunately its hard to provide more help than that. :/
I modified your code a bit to demonstrate what I'm talking about. If you do a simple ngIf="false; else goTemplate" to render the ng-template element, ContentChildren has no problem picking it up bc in that case its actually rendered to the DOM.
https://stackblitz.com/edit/github-ktnw8d-fjk2mu
Upvotes: 5