1

I have a component and I need the list of my content children as TemplateRef.

If I read them with:

@ContentChildren(ToggleComponent) toggles: QueryList<ToggleComponent>;

Then it works, toggles._results is an array of objects of type ToggleComponent, and that's the expected behavior. I want the TemplateRef instead, so I tried:

@ContentChildren(ToggleComponent, {read: TemplateRef}) toggles: QueryList<ToggleComponent>;

But in this case toggles._results is an array of undefineds:

[undefined, undefined, undefined]

Why doesn't it work?

Here is a minimal reproduction of the error, you can see the QueryList object in the console.

  • To get TemplateRef you need to have Embedded template but you haven't – yurzui Nov 25 '17 at 14:18
  • What's an embedded template? – Christian Vincenzo Traina Nov 25 '17 at 19:50
  • 1
    `ng-template` or structural directive represents Embedded view – yurzui Nov 25 '17 at 20:00
  • I don't understand, I don't find any reference about what you say. How can I make work my code? Adding `ng-template` doesn't work. – Christian Vincenzo Traina Nov 25 '17 at 20:05
  • There is no TemplateRef on ToggleComponent. Wrap this component in ng-template and query it like `@ContentChildren(TemplateRef)` – yurzui Nov 26 '17 at 04:18
  • Still not working. Now `toggles._results` is an empty array – Christian Vincenzo Traina Nov 26 '17 at 11:22
  • 1
    Check console https://stackblitz.com/edit/angular-egpsrc?file=app/accordion.component.ts – yurzui Nov 26 '17 at 11:24
  • Ok my mistake was wrapping the serie of ToggleComponent in `ng-template`, instead you wrapped each of them. Anyways I don't like this solution, seriously do we need to change the public interface of the component in order to read the template ref of the ContentChildren? Other users already use my component and I don't want to introduce a breaking change, besides this it also looks ugly and useless, since a user could wonder why he needs to put "ng-template" everywhere. Anyways I don't want to bother you anymore, I'm going to open an issue on Github. Thank you anyways – Christian Vincenzo Traina Nov 26 '17 at 12:00
  • What is the purpose of having TemplateRef from component? TemplateRef is used for structural changes – yurzui Nov 26 '17 at 12:02
  • I want to instantiate the view elsewhere using `ngTemplateOutlet` – Christian Vincenzo Traina Nov 26 '17 at 12:04
  • Hey, you might be interested in this question https://stackoverflow.com/questions/47502461/ng-content-in-for-loop – yurzui Nov 27 '17 at 06:43

0 Answers0