angular - 将模板引用变量绑定(bind)为属性指令类型

标签 angular angular5 angular2-directives angular-directive angular-template

我正在构建一个属性指令,该指令应该获取多个模板,而这些模板又应该包含用于过滤的额外数据,稍后将使用这些数据来选择所需的模板。 因此,我扩展了 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 是否需要其中的指令/组件,或者 ElementRefViewContainerRef (也许还有一些其他标记)。

关于angular - 将模板引用变量绑定(bind)为属性指令类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441085/

相关文章:

Angular ngFor变量赋值

javascript - 如何使用 Angular 中其他 http 服务的输出来调用组件中的 http get 服务?

angular - 访问主机绑定(bind) Angular2 中的下一个 Div

c# - RedirectToAction 不适用于 asp.net core 中的 angular2

angular - Angular2 中嵌套 ngFor 循环的计数器

Angular CLI 错误 : The serve command requires to be run in an Angular project, 但找不到项目定义

angular - 打开第二个时关闭下拉菜单/document.click被点击Angular 5阻止

javascript - 如何在 AngularJS 中使用 pickaday 指令禁用当前和 future 日期

javascript - ionic v3 : Group list by date/day

node.js - 带有 Angular 5 应用程序的 Azure 部署选项未在持续集成中编译和构建