Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 dynamically change the template in the ngTemplateOutlet

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];
like image 728
AngularM Avatar asked Oct 08 '17 16:10

AngularM


1 Answers

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>
like image 109
Günter Zöchbauer Avatar answered Oct 18 '22 00:10

Günter Zöchbauer