20

I have a angular2 component for which the template look like this:

<div>
    <div><ng-template #left></ng-template></div>
    <div><ng-template #right></ng-template></div>
</div>

I would like to be able to retrieve a reference to all ng-template element using ViewChildren but I have no idea the type I need to pass between bracket.

ssougnez
  • 5,315
  • 11
  • 46
  • 79

1 Answers1

32
@ViewChildren(TemplateRef) templates: QueryList<TemplateRef>;

ngAfterViewInit() {
  console.log(this.templates.toArray());
}

or

@ViewChild('left') left:TemplateRef;
@ViewChild('right') right:TemplateRef;

ngAfterViewInit() {
  console.log(this.left, this.right);
}
bvdb
  • 22,839
  • 10
  • 110
  • 123
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 4
    hey, I've just written [an article on DOM manipulation](https://medium.com/@maximus.koretskyi/exploring-angular-dom-abstractions-80b3ebcfc02#.lc9ev4gg0!) using `ViewContainerRef`, take a look if you have time. – Max Koretskyi Mar 05 '17 at 11:17
  • 4
    visual studio code complaints about missing generics: `[ts] Generic type 'TemplateRef' requires 1 type argument(s)` I don't know, shouldn't it be `ElementRef` ? – bvdb Aug 31 '17 at 08:23
  • I'm not able to see what role the generic parameter would fulfill. `TemplateRef` should do IMHO. – Günter Zöchbauer Aug 31 '17 at 08:27
  • 2
    The generic type is meant for the template context object. If you don't use a context object, just use `any`. – Dirk Luijk Jul 09 '18 at 18:29
  • @GünterZöchbauer is it possible to query the template when it's stamped out of ngTemplateOutlet? – Suhayb Dec 20 '18 at 13:41
  • Not sure, but I guess not. As far as I remember it only queries statically added content. – Günter Zöchbauer Dec 20 '18 at 13:42
  • @GünterZöchbauer How to render that `@ViewChild` inside the `.html` template? I get a nice json-dump in `ngAfterViewInit(console.log(…))` but no luck in the html, i.e. ` ` :-( – Frank N Mar 28 '20 at 19:43
  • @FrankNocke Sorry, it's too long ago that I look that I investigated such topics. You'll have to try somewhere else. I don't know. – Günter Zöchbauer Mar 28 '20 at 22:23