动态选择ng-templates

时间:2018-01-29 19:14:13

标签: angular angular-components angular-template

我有一些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属性!

请告知,我不知道如何做我想做的事。

1 个答案:

答案 0 :(得分:1)

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

public tmpls: INamedTmplExample [];

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