I am using Angular2 to create an application i which i need to navigate between tabs using a button present inside the tabs.
my html is as the following :
This can be achieved using selectedIndex input variable using the below code
<md-tab-group [selectedIndex]="selectedIndex">
<md-tab label="Tab 1">Content 1
<button (click)="clickMe()"> click me to go to tab 2 </button>
</md-tab>
<md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>
and your typescript code will be
@Component({
selector: 'tabs-sample',
templateUrl: './tabsSample.html',
})
export class TabsSample {
selectedIndex:number=0;
clickMe(){
this.selectedIndex=1;
}
}
Update 1: Based on comment.
You can use the selectedIndexChange method to fix that error as below
<md-tab-group (selectedIndexChange)="selectedIndexChange($event)"
[selectedIndex]="selectedIndex">
</md-tab-group>
and your code will have
selectedIndexChange(val :number ){
this.selectedIndex=val;
}
Updated in the plunk as well.
LIVE DEMO
you want to use the Angular Router.
try this:
in your html
<md-tab-group>
<md-tab label="one">
<button md-raised-button (click)="goToTwo()">Navigate to Two</button>
<button md-raised-button (click)="goToThree()">Navigate to Three</button>
</md-tab label>
</md-tab-group>
<router-outlet></router-outlet>
inside your component class
constructor(private router: Router) {}
goToTwo() {
this.router.navigate(['two'])
}
goToThree(){
this.router.navigate(['three'])
}
don't forget to import the Router in your component
import { Router } from '@angular/router';
in your module
import { RouterModule, Routes } from '@angular/router';
export const appRoutes: Routes = [
{ path: '',
redirectTo: '/two',
pathMatch: 'full'
},
{ path: 'two', component: TwoComponent,
},
{ path: 'three', component: ThreeComponent }
];
...
imports: [
...,
RouterModule.forRoot(appRoutes)
],
and of course create TwoComponent
and ThreeComponent
.
Hope this helps!