0

I want to know if it is possible to access a template component within ng-template using a template reference variable? I have tried using @ViewChild and @ContentChild but none of them seems to work Example: I want to have access to contents of app-common

<ng-template #first>
<app-common #second><app-common>
</ng-template>

@ViewChild('second') second1: ElementRef;
@ContentChild('second') second2: ElementRef;

ngAfterViewInit() {
  console.log(this.second1);
}

ngAfterContentInit() {
  console.log(this.second2);
}
sevic
  • 879
  • 11
  • 36
Arthur Decker
  • 1,191
  • 3
  • 15
  • 45
  • Can you show what you have tried with "@ContentChild" ? It should work with "@ContentChild". So maybe you did something wrong – PierBJX Aug 28 '18 at 00:32
  • @PierBJX I just added the ContentChild and ViewChild is tried – Arthur Decker Aug 28 '18 at 00:44
  • Did you check the DOM Tree whether the component has actually rendered or not? If it is not present in the DOM tree, then you won't be able to access it. If it is there, then u can access it. – Arjun Panicker Aug 28 '18 at 01:41

1 Answers1

0

The <ng-template> is an Angular element for rendering HTML. It is never displayed directly. In fact, before rendering the view, Angular replaces the <ng-template> and its contents with a comment.

Source

As soon as you use the template somewhere like e.g.:

<ng-content *ngTemplateOutlet="first"></ng-content>

you will also be able to access it's content via a Viewchild.

sevic
  • 879
  • 11
  • 36