md-tabs Using code to goto a tab in angular 2 mate

2019-01-15 11:02发布

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 :

<md-tab-group>
<md-tab label="one">
   <button md-raised-button>Navigate to Two</button>
   <button md-raised-button>Navigate to Three</button>
</md-tab label>
<md-tab label="two">
</md-tab label>
<md-tab label="three"> 
</md-tab label>
</md-tab-group>

So,when i click the navigate to three it should take me to the tab name three

I am using the Angular2 material design for this example can anyone know to solve this problem.

Thanks in advance

2条回答
smile是对你的礼貌
2楼-- · 2019-01-15 11:19

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

查看更多
小情绪 Triste *
3楼-- · 2019-01-15 11:29

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!

查看更多
登录 后发表回答