使用一个函数来确定要使用 ngTemplateOutlet 呈现哪个模板

Use a function to determine which template to render with ngTemplateOutlet

有没有办法使用函数来确定使用 *ngTemplateOutlet 呈现哪个模板?我正在努力使它尽可能独立。目的是可以将此自定义选项卡组件添加到通用组件库中,用户可以在调用组件时提供自己的模板。

现在,我有:

<ng-container *ngTemplateOutlet="getTemplate()"></ng-container>

<ng-template #tab1> TAB1 STUFF </ng-template>
<ng-template #tab2> TAB2 STUFF, WHICH IS WAY DIFFERENT </ng-template>

where getTemplate() returns this.selectedTab.selector(“tab1”或“tab2”),但这不起作用。最简单、最干净的修复方法是什么?目标是将尽可能多的逻辑包含在选项卡组件中,因为这将被添加到公共库中。这也意味着简单地使用 *ngIf 可能并不理想,因为可能有多个选项卡并且最初可能不需要呈现所有可能复杂的内容。

我工作的沙盒是 here

我们不能将字符串传递给 ngTemplateOutlet 指令。但你可以这样做:

    <ng-container
      [ngTemplateOutlet]='{ "tab1": tab1, "tab2": tab2}[getTemplate()]'
    ></ng-container>  

   <ng-template #tab1></ng-template>
   <ng-template #tab2></ng-template>

getTemplate 方法 returns 字符串,我们已将该字符串映射到模板引用变量(tab1、tab2)。检查更新后的沙箱 here.

但这里更好的方法是使用 ngSwitch 指令。