A
A
Artem2018-08-03 17:54:10
Angular
Artem, 2018-08-03 17:54:10

How to get a reference to an element inside an angular 2+ function?

The classic way to get a link to an element on the page is via ViewChild, ContentChild, etc. with a selector.
for example

@ContentChild('element') element: ElementRef;
@ContentChild('template') template: TemplateRef<any>;

What to do when it is not known in advance which selector to search for an element?
More details:
There is a component inside which ng-template (TemplateRef) templates are passed. Each template receives previously unknown identifiers or template variables:
// app.component.html
<app-foo>
   <ng-template #one>One</ng-template>
   <ng-template #two>Two</ng-template>
</app-foo>

Inside the component, depending on some conditions, one of the received templates is displayed:
// foo.component.html
<ng-template [ngTemplateOutlet]="GetTemplate('one')"></ng-template>

How to do something like this:
// foo.component.ts
...
@ContentChildren(TemplateRef) templates: QuerySelector<TemplateRef<any>>;
...
private GetTemplate(name: string) {
   const searchedTemplate = this.templates.get(name);
   return searchedTemplate;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem, 2018-08-06
@Cruper

Solution via directive:

@Input() appTemplateName: string;

constructor(protected template: TemplateRef<any>) { }

public get Template(): TemplateRef<any> {
    return this.template;
}

@ContentChildren(TemplateNameDirective) templates: QueryList<TemplateNameDirective>;
...
return this.templates.find(template => template.appTemplateName === requiredName).Template;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question