【问题标题】:Angular dynamically display templates with *ngTemplateOutlet, based on component variableAngular 基于组件变量使用 *ngTemplateOutlet 动态显示模板
【发布时间】:2019-07-28 00:04:33
【问题描述】:

首先让我说,我确实查看了有关 ngTemplateOutlet 的其他几个问题(例如:Angular 2 dynamically change the template in the ngTemplateOutletngTemplateOutlet with dynamic value),但它们并没有真正涵盖我想要做的事情,或者也许我可以'看不出如何将逻辑应用于我想要实现的目标。

我的目标:

我有一个页面,我希望能够更改模板的显示顺序。

我有 2 个简单的模板,“颜色”和“字体”:

<ng-template #colors>
  Red: #FF0000
  Green: #00FF00
  Blue: #0000FF
</ng-template>

<ng-template #fonts>
  Helvetica
  Verdana
  Times New Roman
</ng-template>

按预定义的顺序显示这些没有问题:

<div>
  <ng-container *ngTemplateOutlet="colors"></ng-container>
</div>
<div>
  <ng-container *ngTemplateOutlet="fonts"></ng-container>
</div>

我的问题是,我不知道如何根据组件上的变量显示这些模板。 我的组件包含一个数组变量,其中包含我要显示的模板的顺序和名称:

public order: ['fonts', 'colors'];

这里注意,模板的顺序是切换的,所以“字体”应该先显示,然后是“颜色”。

我的想法是根据 order 变量分配 *ngTemplateOutlet 值,如下所示:

<ng-container [ngTemplateOutlet]="order[0]"></ng-container>
<ng-container [ngTemplateOutlet]="order[1]"></ng-container>

但是当我这样做时,我得到以下控制台错误:

TypeError: templateRef.createEmbeddedView is not a function

我不确定我哪里出了问题,或者我如何让 *ngTemplateOutlet 从我的组件上的数组变量中获取它的模板名称。

我为它创建了这个堆栈闪电战:https://stackblitz.com/edit/angular-q7uqbx

任何帮助将不胜感激!

亲切的问候,

杰斯帕

【问题讨论】:

  • 最好的方法是遵循 dynamic components 指南,该指南解释了一切如何运作以及如何使用它。
  • 这似乎与动态更改组件更相关 - 一旦我的组件调用 OnInit(),模板的顺序就设置好了,所以这似乎有点矫枉过正。我基本上需要更改 &lt;ng-container *ng-templateOutlet="cars"&gt; 中的“汽车”以从组件中读取,而且我已经看到了多个使用 ViewChild 做非常相似的事情的例子,所以我想用这种方法应该是可行的,我只是没有还没弄明白
  • 好吧,如果您还没有看到它,那么您正在动态更改组件。但适合你自己,我不是有问题的人。祝你好运!
  • 也许我对自己的解释不够好,但如果你看看@taras-d 的建议答案,那更符合我的想法

标签: angular


【解决方案1】:

您需要使用 ViewChild 来获取对模板的引用并将模板存储在数组中。

组件:

import { Component, ViewChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('colors') colors: TemplateRef<any>;
  @ViewChild('fonts') fonts: TemplateRef<any>;

  public order = [];

  ngAfterViewInit(): void {
    this.order = [this.fonts, this.colors];
  }
}

模板:

<ng-template #colors>
  Red: #FF0000
  Green: #00FF00
  Blue: #0000FF
</ng-template>

<ng-template #fonts>
  Helvetica
  Verdana
  Times New Roman
</ng-template>

<ng-container [ngTemplateOutlet]="order[0]"></ng-container>
<ng-container [ngTemplateOutlet]="order[1]"></ng-container>

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2017-05-14
    • 2017-03-24
    • 2019-04-08
    相关资源
    最近更新 更多