![](/img/trans.png)
[英]Injecting component to ng-container? (load ng-template from file)
[英]Dynamically populate an ng-container based on a list of ng-template that are TemplateRef in component.ts
为了进一步解释,我想根据 ng 模板列表填充一个 ng 容器。 每个 ng-template 一个接一个地添加。 换句话说,ng-template 包含两个按钮 previous 和 next。 previous 删除当前的 ng-template 并返回以前的模板。 Next 按钮删除当前的 ng-template 并添加下一个 ng-template。
我的问题是在 component.ts 中使用 TemplateRef 引用每个模板。 我尝试从 component.ts 构造函数获取每个模板引用,但这不起作用。 我下面的代码解释了我使用的方法。
home.component.html
<div class="template-container">
<!-- Ng Container -->
<ng-container *ngTemplateOutlet="activeTemplate">
</ng-container>
<!-- Select Service -->
<ng-template #allServices>
<!-- TODO -->
</ng-template>
<!-- Select Worker -->
<ng-template #worker>
<!-- TODO -->
</ng-template>
<!-- Display Calendar -->
<ng-template #calendar>
<!-- TODO -->
</ng-template>
<!-- User entails user details -->
<ng-template #userDetails>
<!-- TODO -->
</ng-template>
</div>
主页.component.ts
import { Component, VERSION, TemplateRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular ' + VERSION.full;
templates: TemplateRef<any>[] = [];
activeTemplate: TemplateRef<any>;
constructor(private templateRef: TemplateRef<any>) {
this.templates = [
this.templateRef.allServices, // Error occurs
this.templateRef.worker, // Error occurs
this.templateRef.calendar, // Error occurs
this.templateRef.userDetails // Error occurs
];
this.activeTemplate = this.templates[0];
}
}
您可以看到我是如何尝试提取每个参考文献的,但这不起作用。 我还应该说我是 Angular 的新手,我从 angular 阅读了TemplateRef
的文档,据我所知, ElementRef
应该是模板的参考。
当您在构造函数 templateRef 中注入时,这是关于您的组件 home.component 的。 您需要使用 ViewChild 获取模板
ViewChild('allServices',{static:true}) template0:TemplateRef<any>
ViewChild('worker',{static:true}) template1:TemplateRef<any>
ViewChild('calendar',{static:true}) template2:TemplateRef<any>
ViewChild('userDetails',{static:true}) template3:TemplateRef<any>
并使用
index=0;
this.activeTemplate = this['template'+index];
但是你在 ngOnInit 中分配变量ngOnInit
(如果你不使用{static:true}
则在 ngAfterViewInit 中)而不是在构造函数中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.