问题
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