从查询列表中识别特定的Angular TemplateRef [英] Identify specific Angular TemplateRef from a QueryList

查看:62
本文介绍了从查询列表中识别特定的Angular TemplateRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 6/7中,我有一个向其中投射内容的组件( ParentComponent 模板):

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>

MyComponent 类中,我可以使用 ContentChildren 装饰器获得所有模板的 QueryList :

In the MyComponent class, I can get a QueryList of all the templates using the ContentChildren decorator:

@ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;

挑战在于,我想在通过 @Input()templateNames 设置的 ParentComponent 标识的特定模板上执行代码.

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?
}

问题是我不知道如何读取 name 属性或在 ParentComponent ng-template 标记上设置的其他内容>.我不知道如何区分一个TemplateRef与另一个;

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;

请记住, MyComponent 不能对将使用什么名称或是否应处理所有 ng-templates 做出任何假设,这是我示例中的最后一个上面的内容不会在 @Input()templateNames 中列出,因此不会被处理.我可以在 ParentComponent 中进行设置,以帮助我区分两个 TemplateRef 的区别吗?

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?

推荐答案

您可以使用名称输入参数创建指令:

You can create a directive with a name input parameter:

@Directive({
  selector: '[template-name]'
})
export class TableColumnDirective {

  constructor(public readonly template: TemplateRef<any>) { }

  @Input('template-name') columnName: string;
}

使用这种方式:

  <my-component>
      <ng-template template-name="t1">...</ng-template>
      <ng-template template-name="t2">...</ng-template>
      ...

然后在 my-component 中以这种方式注入:

And then in my-component inject that way:

@ContentChildren(TableColumnDirective) templates: QueryList<TableColumnDirective>;

有关更详细的说明/示例,请参见接受的答案

For a more detailed explanation/example look at the accepted answer from this question

这篇关于从查询列表中识别特定的Angular TemplateRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆