通过 Id 获取 ViewChildren 模板

Get ViewChildren Template By Id

在我的组件中,我通过使用 ViewChildren 获得了它的标记模板列表:

@ViewChildren(TemplateRef) private _templates: QueryList<TemplateRef<unknown>>;

在 Angular8 中我无法通过 Id 过滤它们,所以我需要寻找一个内部 属性 - 这在某种程度上有点 hacky:

let template = this._templates.find(t => (<any>t)._def.references[id]) : null;

现在,Angular 9 不再适用。我检查了对象,发现了一个新的 "hack":

this._templates.find(t => (<any>t)._declarationTContainer?.localNames?.includes(id)) : null;

但是对于这种情况是否有任何新的或干净的解决方案?

仍然希望有一个无需自定义指令即可工作的解决方案,例如。 MatTab 可能也会做类似的事情:

<mat-tab>
    <ng-template mat-tab-label>
        ...
    </ng-template>

    <ng-template matTabContent>
        ...
    </ng-template>
</mat-tab>

针对您的场景的一个干净的解决方案是使用 ng-template[name] 选择器创建一个 NgTemplateNameDirective 指令:

import { Directive, Input, TemplateRef } from '@angular/core';

@Directive({
  selector: 'ng-template[name]'
})
export class NgTemplateNameDirective {
  @Input() name: string;

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

之后创建如下模板:

<ng-template name="t1"></ng-template>
<ng-template name="t2"></ng-template>

然后查询 NgTemplateNameDirective 而不是 TemplateRef:

@ViewChildren(NgTemplateNameDirective) private _templates: QueryList<NgTemplateNameDirective>;

最后按名称搜索您的模板

getTemplateRefByName(name: string): TemplateRef<any> {
  const dir = this._templates.find(dir => dir.name === name);
  return dir ? dir.template : null
}

在两个视图引擎中工作正常:ViewEngine 和 Ivy

Ng-run Example