In Angular 6/7, I have a component into which I am projecting content like so (ParentComponent template):
<my-component [templateNames]="['t1', 't2']">
<ng-template name="t1">...</ng-template>
<ng-template name="t2">...</ng-template>
<ng-template>...</ng-template> <!-- not included in [templateNames] -->
</my-component>
In the MyComponent
class, I can get a QueryList of all the templates using the ContentChildren decorator:
@ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;
The challenge is that I want to execute code on specific templates identified by what ParentComponent set via the @Input() templateNames
.
processTemplates() {
for (const name of this.templateNames) {
const templateRef = this.getTemplateByName(name);
this.doWork(templateRef);
}
}
getTemplateByName(name) {
const templates = this.templates.toArray();
return templates.find(t => ?); // what can I query to distinguish templates?
}
Problem is that I don't know how to read the name
attribute or anything else I set on the ng-template tag in ParentComponent. I have no idea how to distinguish one TemplateRef from another;
Keep in mind that MyComponent cannot make any assumption on what names will be used, or whether all ng-templates should be processed -- the last one in my example above should not get processed because it's not listed in the @Input() templateNames. Is there anything I can set in ParentComponent that will help me tell the two TemplateRef's apart?