问题
Hi I have been stuck on what seems like this simple problem for a while going back and forth through SO solutions does not seem to fit my use case exactly... I have an angular component which has a template containing bootstrap nav pills, these are just being used as tabs within this particular screen. So I have a Search tab and a results tab and after performing a search I want to activate the results tab but I can't work out how to hook into the bootstrap tabs from the component.
The template ...
<div id="tabs" #tabs>
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link active" href="#search" data-toggle="tab">Search</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#results" data-toggle="tab">Results</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="search">
search screen
<button type="button" (click)="search()">Search</button>
</div>
<div class="tab-pane active" id="results">results screen</div>
</div>
</div>
Then the component is like..
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html'
})
export class DemoComponent implements OnInit {
@ViewChild('tabs') tabs;
search() {
//perform search. then select the results tab in template.
//this.tabs.selectedIndex = ...
}
}
Is this possible? or do I need to be using a different flavour of tabs which are configured in the component. Many thanks in advance.
回答1:
Keep a track of which tab is active using activeTab and use ngClass to apply .active class
component.html
<div id="tabs" #tabs>
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link active" href="#search" [ngClass]="{ 'active':activeTab==='search'}" (click)="search('search')"
data-toggle="tab">Search</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#results" [ngClass]="{ 'active':activeTab==='result'}" data-toggle="tab"
(click)="result('result')">Results</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="search" [ngClass]="{ 'active':activeTab==='search'}">
search screen
<button type="button" (click)="search('result')">Search</button>
</div>
<div class="tab-pane" id="results" [ngClass]="{ 'active':activeTab==='result'}">results screen</div>
</div>
</div>
component.ts
activeTab = 'search';
search(activeTab){
this.activeTab = activeTab;
}
result(activeTab){
this.activeTab = activeTab;
}
来源:https://stackoverflow.com/questions/51105507/change-active-bootstrap-tab-inside-angular-component