[英]Get ViewChildren Template By Id
在我的组件中,我使用 ViewChildren 获取了其标记模板列表:
@ViewChildren(TemplateRef) private _templates: QueryList<TemplateRef<unknown>>;
在 Angular8 中,我无法通过 Id 过滤它们,所以我需要寻找一个内部属性 - 这在某种程度上有点笨拙:
let template = this._templates.find(t => (<any>t)._def.references[id]) : null;
现在,使用 Angular 9,这不再起作用。 我检查了对象,发现了一个新的“黑客”:
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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.