动态选择 ng-templates

Dynamically selecting ng-templates

我有一些 Angular 模板,我希望它们能够动态 select 并显示在组件模板的特定区域中。下面是我正在尝试做的一些简化示例代码。

我似乎以这种方式使用 @ViewChild 到 "save" 对 class 属性 的模板引用要么不起作用,要么我在这里误解了一些东西。

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 属性!

请指教,我不知道如何才能在这里做我想做的事情。

尝试在 ngAfterViewInit 挂钩中收集您的 ViewChild 元素:

public tmpls: INamedTmplExample [];

ngAfterViewInit() {
    this.tmpls = [
        { name: 'One', template: this.tmpl1},
        { name: 'Two', template: this.tmpl2},
    ];
}