将模板引用变量绑定为属性指令类型

Bind template reference variable as an attribute directive type

我正在构建一个属性指令,它应该获取多个模板,而这些模板又应该包含用于过滤的额外数据,这些数据稍后将用于选择所需的模板。 所以我扩展了 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 被构造了两次,在分配带有模板的数组之前,并且 filter 也被分配了,虽然过滤器的分配发生在模板数组的分配之后。 我试过在构造数组时进行强制转换,如下所示:

<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 是否需要 directive/component从它,或 ElementRef,或 ViewContainerRef(也许还有其他一些标记)。

好吧,现在看来答案是显而易见的,只是在表面上-只是在Directive decorator上添加exportAs 属性,然后将引用赋值给模板引用变量,与 ngForm...

非常相似