Answer the question
In order to leave comments, you need to log in
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>;
// app.component.html
<app-foo>
<ng-template #one>One</ng-template>
<ng-template #two>Two</ng-template>
</app-foo>
// foo.component.html
<ng-template [ngTemplateOutlet]="GetTemplate('one')"></ng-template>
// 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
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 questionAsk a Question
731 491 924 answers to any question