根据component.ts中TemplateRef的ng-template列表动态填充ng-container.<



为了进一步解释,我想基于ng模板列表填充一个ng容器。每个ng-template都是一个接一个添加的。换句话说,ng-template包含两个按钮previous和next。Previous删除当前ng-template并返回上一个模板。Next按钮删除当前的ng-template,并添加下一个ng-template。

我的问题是在component.ts中使用TemplateRef引用每个模板。我试着从组件中获取每个模板引用。t的构造函数,但这不起作用。下面的代码解释了我使用的方法。

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>

home.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];

但是你赋值变量activeTemplate在ngOnInit(或在ngAfterViewInit如果你不使用{static:true})not在构造函数

看到stackblitz

最新更新