Angular 2 dynamically change the template in the ngTemplateOutlet

断了今生、忘了曾经 提交于 2019-12-04 23:38:41

问题


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];

回答1:


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>


来源:https://stackoverflow.com/questions/46633431/angular-2-dynamically-change-the-template-in-the-ngtemplateoutlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!