【发布时间】:2018-07-08 13:40:38
【问题描述】:
我有一些 Angular 模板,我希望它们能够动态选择并显示在组件模板的特定区域中。下面是我正在尝试做的一些简化示例代码。
我似乎使用@ViewChild 以这种方式“保存”对类属性的模板引用要么不起作用,要么我在这里误解了一些东西。
在example.component.ts
import { Component, TemplateRef, ViewChild } from '@angular/core';
interface INamedTmplExample {
name: string;
template: TemplateRef<object>;
}
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class BulkActionsComponent {
@ViewChild('templateOne') private tmpl1: TemplateRef<object>;
@ViewChild('templateTwo') private tmpl2: TemplateRef<object>;
public tmpls: INamedTmplExample [] = [
{ name: 'One', template: this.tmpl1},
{ name: 'Two', template: this.tmpl2},
];
public selectedTmpl: INamedTmplExample | undefined;
public selectTemplate(tmpl: INamedTmplExample ): void {
this.selectedTmpl= tmpl;
}
}
然后在example.component.html:
<h1>Choose One</h1>
<button type="button"
*ngFor="let t of tmpls"
(click)="selectTemplate(t)">
{{t.name}}
</button>
<ng-container *ngIf="selectedTmpl">
<h2>You have selected {{selectedTmpl?.name}}</h2>
<ng-container *ngTemplateOutlet="selectedTmpl?.template"></ng-container>
</ng-container>
<ng-template #templateOne>
<h3>One</h3>
</ng-template>
<ng-template #templateTwo>
<h3>Two!</h3>
</ng-template>
我也试过这样调试:
<pre class="border bg-light p-2">{{tmpls| json}}</pre>
<pre class="border bg-light p-2">{{selectedTmpl| json}}</pre>
但这只是显示INamedTmplExample 对象,省略了template 属性!
请指教,我不确定如何在这里做我想做的事情。
【问题讨论】:
-
public tmpls: INamedTmplExample [] = ...可能在ViewChild元素可用之前运行。也许您可以尝试在ngAfterViewInit中运行它。 -
我不确定我是否理解您的意思,但请记住,这是示例代码,还有比这更多的模板。我宁愿每次添加新模板时都不必添加新的 if 语句
标签: angular angular-components angular-template