I'm building an attribute directive that should get several templates which in turn should contain extra data for filtering that would be used later to selected the required template. So I've extended the TemplatePortalDirective as follows:
@Directive({
selector: "[filter]ng-template"
})
export class FilterableTemplateDirective extends TemplatePortalDirective {
@Input() filter: string;
constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef
{
super(templateRef, viewContainerRef);
}
}
and my attribute directive, named TemplateSelector
has an @Input
that is used also as the selector by attribute:
@Directive({
selector: "[templateSelector]"
})
...
@Input("templateSelector") templates: FilterableTemplateDirective[]
Now, lets assume I have the following template:
<div templateSelector="[templateA, templateB]"></div>
<ng-template filter="div[data-type-a]" #templateA>
...
</ng-template>
<ng-template filter="div[data-type-b]" #templateB>
...
</ng-template>
So, when I'm trying to access this.templates
from a method within TemplateSelector
I'm getting the array, but it's of type TemplateRef
, that is, plain ng-template
, with no extra fields, though when I was debugging I've seen that FilterableTemplateDirective
was constructed twice, before the array with the templates was assigned, and the filter
also was assigned, though the assignment of filters happened later than the assignment of the array with the templates.
I've tried to cast upon constructing of the array, like so:
<div templateSelector="[templateA as FilterableTemplateDirective, templateBtemplateA as FilterableTemplateDirective]"></div>
or so:
<div templateSelector="[<FilterableTemplateDirective>templateA, <FilterableTemplateDirective>templateBtemplateA]"></div>
neither of which succeeded, the app just crashes saying that it was expecting the end of array instead of as
or the angle brackets...
Well, now it seems that the answer is obvious and was lying on the surface - just to add exportAs
property on the Directive decorator
, then to assign the reference to the template reference variable, quite similar to the ngForm
...