<div class="main__container"> <ng-template #test></ng-template> <ng-template #test2></ng-template> </div>
我通过以下方式检索对所有TemplateRef的引用:
@ViewChildren(TemplateRef) private templates;
对于所有这些,我如何检索相关变量的名称?因此,对第一个模板进行“测试”,对另一个模板进行“test2”.我不是绝对想要使用变量,如果可以使用ng-template的属性,那就没关系.我尝试使用TemplateRef,ViewContainerRef和ElementRef,但每次都会返回对comment元素的引用.
解决方法
@ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>; getTemplate(id: string): TemplateRef<any> { // FIXME: Should not use private API... return this.templates ? this.templates.find((template: any) => template._def.references[id]) : null; }
但这不适用于生产构建,实际上我发现你的帖子正在寻找另一个解决方案,如果我找到了某些内容或者向Angular github提交功能请求,我会更新.
与此同时,我认为值得分享.
– 编辑 –
看起来确实存在使用结构指令的可能解决方案.
You’ll learn in this guide that the asterisk (*) is a convenience notation and the string is a microSyntax rather than the usual template expression. Angular desugars this notation into a marked-up
<ng-template>
that surrounds the host element and its descendents. Each structural directive does something different with that template.
– 编辑2 –
好吧,它适用于检索TemplateRef的指令,但是目前我使用id将其注册到服务,我不再使用ViewChildren / ContentChildren了.使用* ngTemplateOutlet指令的My Component然后使用该服务检索TemplateRef.
这是指令源代码:
@Directive({ selector: '[formeTemplate]' }) export class FormeTemplateDirective { @Input('formeTemplate') templateId; constructor(private host: TemplateRef<any>,private service: FormeTemplateService) { } ngOnInit() { this.service.register(this.templateId,this.host); } }
服务 :
@Injectable() export class FormeTemplateService { private templates: Array<FormeTemplate>; constructor() { this.templates = new Array(); } register(id: string,ref: TemplateRef<any>) { this.templates.push(new FormeTemplate(id,ref)); } getTemplateRef(templateId: string) : TemplateRef<any> { let template = this.templates.find((template) => template.id === templateId); return template ? template.ref : null; } }