7

I want to dynamically change the template in the ngTemplateOutlet. The ngTemplateOutlet would change when the selectedTab changes.

I have two basic templates below called #Tab1 and #Tab2.

Note: I'm using angular version 4.

Tab Menu Example (HTML):

<div class="tabMenu">   
    <ul>
        <li *ngFor="let tab of tabLinks" [class.active]="selectedTab.name === tab.name">
            <a (click)="selectedTab = tab">{{ tab.name }}</a>
        </li>
    </ul>

    <div class="tabContent">        
        <tab [data]="selectedTab.data">
            <ng-container *ngTemplateOutlet="selectedTab.name;context:selectedTab"></ng-container>
        </tab>

        <ng-template class="tab1" #Tab1 let-test="data">
            <p>Template A - {{ test }}</p>          
        </ng-template>

        <ng-template class="tab1" #Tab2 let-test="data">
            <p>Template B - {{ test }}</p>          
        </ng-template>

    </div>
 </div>

This is the basic typescript array:

tabLinks: Array<Object> = [
    {
        name: "Tab1",
        data: "data tab 1"
    },
    {
        name: "Tab2",
        data: "data tab 2"
    }
];

selectedTab: Object = this.tabLinks[0];
AngularM
  • 15,982
  • 28
  • 94
  • 169

1 Answers1

8

If you use @ViewChild() instead of a direct template variable reference, you can use this['foo'] to access a field named foo:

@ViewChild('Tab1') tab1:TemplateRef<any>;
@ViewChild('Tab2') tab2:TemplateRef<any>;
    <ng-template class="tab1" #Tab1 let-test="data">
        <p>Template A - {{ test }}</p>          
    </ng-template>

    <ng-template class="tab1" #Tab2 let-test="data">
        <p>Template B - {{ test }}</p>          
    </ng-template>
        <ng-container *ngTemplateOutlet="this[selectedTab.name];context:selectedTab"></ng-container>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I did the above changes. I don't get any console errors, but no template is attached to the ng-container – AngularM Oct 08 '17 at 16:50
  • Sorry, no idea. I can't debug from here. If you create a https://stackblitz.com/ or Plunker that allows to reproduce, I can investigate. – Günter Zöchbauer Oct 08 '17 at 16:52
  • That's because you changed the casing in the `tabLinks` data :D I changed the casing to match your data. I'd suggest to keep it as you have it in your data in the stackblitz. I updated my answer. https://stackblitz.com/edit/angular-bx7f2p – Günter Zöchbauer Oct 08 '17 at 17:03
  • this doesn't work, selectedTab is also a component variable. this['tab1'] however works since it tries to access component variable tab1 which is a templateref.. I donno how to make this work in Angular 12 , I m tired! – minigeek Jul 07 '21 at 12:51