Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewChildren for ng-template

Tags:

angular

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.

like image 204
ssougnez Avatar asked Mar 02 '17 22:03

ssougnez


People also ask

How do you use ViewChildren?

Descriptionlink. Use to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value. View queries are set before the ngAfterViewInit callback is called.

What is pTemplate in ng-template?

pTemplate is a custom-made directive by PrimeNG. Its purpose is to link a template defined by you (the user) to a container defined by the library (PrimeNG). That enables the user to provide a custom template that is displayed inside a component made by the library.

What is the difference between ViewChild () and ContentChild ()?

ViewChild is used to select an element from component's template while ContentChild is used to select projected content.

What is difference between ViewChild and ViewChildren?

Working with @ViewChildren is similar to @ViewChild, but the difference between the two is @ViewChildren provides a list of element references rather than returning a single reference. It is used to reference multiple elements. We can then iterate the list of the element referenced by the variable.


1 Answers

@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);
}
like image 146
Günter Zöchbauer Avatar answered Sep 22 '22 20:09

Günter Zöchbauer