我正在构建一个属性指令,该指令应该获取多个模板,而这些模板又应该包含用于过滤的额外数据,稍后将使用这些数据来选择所需的模板。 因此,我扩展了 TemplatePortalDirective,如下所示:
@Directive({
selector: "[filter]ng-template"
})
export class FilterableTemplateDirective extends TemplatePortalDirective {
@Input() filter: string;
constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef
{
super(templateRef, viewContainerRef);
}
}
我的属性指令,名为TemplateSelector
有一个@Input
,它也用作属性选择器:
@Directive({
selector: "[templateSelector]"
})
...
@Input("templateSelector") templates: FilterableTemplateDirective[]
现在,假设我有以下模板:
<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>
因此,当我尝试从 TemplateSelector
中的方法访问 this.templates
时,我得到了数组,但它的类型为 TemplateRef
,即普通的 ng-template
,没有额外的字段,尽管在调试时我发现 FilterableTemplateDirective
在数组之前被构造了两次分配了模板,并且还分配了过滤器,尽管过滤器的分配发生在带有模板的数组分配之后。
我尝试在构建数组时进行强制转换,如下所示:
<div templateSelector="[templateA as FilterableTemplateDirective, templateBtemplateA as FilterableTemplateDirective]"></div>
左右:
<div templateSelector="[<FilterableTemplateDirective>templateA, <FilterableTemplateDirective>templateBtemplateA]"></div>
两者都没有成功,应用程序只是崩溃了,说它期待数组的结尾而不是 as
或尖括号...
最佳答案
如果您的模板具有灵活性,那么您可以使用 @ContentChildren 实现您想要的效果如下:
<div templateSelector>
<ng-template filter="div[data-type-a]">
...
</ng-template>
<ng-template filter="div[data-type-b]">
...
</ng-template>
</div>
和你的templateSelector
指令:
@Directive({
selector: "[templateSelector]"
})
...
@ContentChildren(FilterableTemplateDirective)
templates: QueryList<FilterableTemplateDirective>;
当使用模板变量标记元素时,您会受到限制,因为您无法告诉 Angular 您想要从该元素中得到什么。通过 @ContentChildren
、@ContentChild
、@ViewChild
和 @ViewChildren
等模板查询,您可以灵活地进行查询告诉 Angular 是否需要其中的指令/组件,或者 ElementRef
或 ViewContainerRef
(也许还有一些其他标记)。
关于angular - 将模板引用变量绑定(bind)为属性指令类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441085/