angular - 从 QueryList 中识别特定的 Angular TemplateRef

标签 angular angular-template angular-template-variable

在 Angular 6/7 中,我有一个组件,我将内容投影到其中(ParentComponent 模板):

<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:
@ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;

挑战在于我想在由 ParentComponent 通过 @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 和另一个;

请记住,MyComponent 不能对将使用什么名称或是否应该处理所有 ng-templates 做出任何假设——我上面示例中的最后一个不应被处理,因为它没有在 @Input() 模板名称中列出。我可以在 ParentComponent 中设置什么来帮助我区分这两个 TemplateRef 吗?

最佳答案

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

@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以这种方式注入(inject):
@ContentChildren(TableColumnDirective) templates: QueryList<TableColumnDirective>;
有关更详细的解释/示例,请查看已接受的答案 from this question

关于angular - 从 QueryList 中识别特定的 Angular TemplateRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52903851/

相关文章:

angular - NGRX reducer 多个实例的选择器

angular - 没有 InjectionToken 本地化键前缀的提供者

javascript - float 操作按钮不滚动

angular - 从 Angular 中的模板引用变量中获取 ElementRef

javascript - 为模板中的变量赋值 - Angular7

javascript - 检查字段是否已使用 angular 6 和 firestore 进行修改

angular - ng2 - ng-container 和 ng-template 标签之间的区别

angularjs - 如何从 Grails 插件提供的 JS 文件中指向 AngularJS 模板?

javascript - 如何在 Angular 模板中显示日期和时间并保持更新?

Angular 引用# vs ngModel