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

后端 未结 2 1286
暖寄归人
暖寄归人 2020-12-06 14:23

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 :

         


        
相关标签:
2条回答
  • 2020-12-06 14:47

    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

    0 讨论(0)
  • 2020-12-06 15:06

    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!

    0 讨论(0)
提交回复
热议问题