我有一些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属性!
请告诉我,我不确定我如何才能在这里做我想做的事情。
发布于 2018-01-30 03:24:43
尝试在ngAfterViewInit钩子中收集ViewChild元素:
public tmpls: INamedTmplExample [];
ngAfterViewInit() {
this.tmpls = [
{ name: 'One', template: this.tmpl1},
{ name: 'Two', template: this.tmpl2},
];
}https://stackoverflow.com/questions/48508398
复制相似问题