Search code examples
angularcomponents

Use a function to determine which template to render with ngTemplateOutlet


Is there a way to use a function to determine which template is rendered with *ngTemplateOutlet ? I'm trying to keep this as self-contained as possible. The intent is that this custom tab component can be added to a library of common components, where the user will be able to provide their own templates when the component is called.

Right now, I have:

<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 (either "tab1" or "tab2"), but that doesn't work. What is the simplest, cleanest fix for this? The goal is to keep as much of the logic as possible contained within the tab component, since that's what would get added to the common library. This also means that simply using *ngIf may not be ideal, since there could be several tabs and rendering all the possibly-complex content initially may not be desired.

The sandbox in which I'm working is here.


Solution

  • We cannot pass a string to the ngTemplateOutlet directive. But you could do this:

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

    The getTemplate method returns the string and we have mapped that string to a Template Reference variable (tab1, tab2). Checkout the updated sandbox here.

    But the better approach here is to use the ngSwitch directive.