【问题标题】:Dynamically selecting ng-templates动态选择 ng-templates
【发布时间】: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


【解决方案1】:

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

public tmpls: INamedTmplExample [];

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

【讨论】:

  • 我最终不得不改用ngOnInit。使用ngAfterViewInit 给了我不相关的错误“无法读取未定义的属性'名称'”,即使我将属性name 更改为不同的名称,它仍然给我这个错误。我知道那是什么,但无论如何这样做可以修复它并使模板的东西也可以工作。
猜你喜欢
  • 2020-03-18
  • 1970-01-01
  • 2015-06-14
  • 2016-09-09
  • 2018-05-24
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多