2

This is component.html part. How can I change to next tab from button of tab1 to tab2 and tab2 to tab 3 and so on?

<mat-tab-group>
    <mat-tab label="First"> Content 1 
        <button (click)=?>next</button>
    </mat-tab>
    <mat-tab label="Second"> Content 2
        <button (click)=?>previous</button>
        <button (click)=?>next</button>
    </mat-tab>
    <mat-tab label="Third"> Content 3
        <button (click)=?>previous</button>
        <button (click)=?>submit</button>
    </mat-tab>
</mat-tab-group>
1
  • in content of mat-tab i want to make button which will help me switching to next tab? Commented Feb 21, 2019 at 2:03

2 Answers 2

2

Consider following the tab-panel html structure.

<mat-tab-group #allTabs>
  <mat-tab label="Tab 1">
    <p>Tab 1 Content</p>
    <button mat-raised-button tabindex="-1" type="button" 
     color="warn" (click)='moveToSelectedTab("Tab 2")'>Move to Tab 2</button>
  </mat-tab>
  <mat-tab label="Tab 2">
    <p>Tab 2 Content</p>
    <button mat-raised-button tabindex="-1" type="button" 
    color="warn" (click)='moveToSelectedTab("Tab 1")'>Move to Tab 1</button>
  </mat-tab>
</mat-tab-group>

You can find all the tabs in the component, and look for the tab label you want to move,
after that call the click method on that.

moveToSelectedTab(tabName: string) {
  for (let i =0; i< document.querySelectorAll('.mat-tab-label-content').length; i++) {
  if ((<HTMLElement>document.querySelectorAll('.mat-tab-label-content')[i]).innerText == tabName) 
     {
        (<HTMLElement>document.querySelectorAll('.mat-tab-label')[i]).click();
     }
   }
}

Demo showing Tab Switching from Button present in content of different tab

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the selectedIndex attribute of the MatTabGroup component.

HTML:

<mat-tab-group #tabgroup>
  
  <mat-tab label="First"> Content 1 
    <button (click)="changeIndex(tabgroup,1)">next</button>
  </mat-tab>
  
  <mat-tab label="Second"> Content 2
    <button (click)="changeIndex(tabgroup,0)">previous</button>
    <button (click)="changeIndex(tabgroup,2)">next</button>
  </mat-tab>
  
  <mat-tab label="Third"> Content 3
    <button (click)="changeIndex(tabgroup,1)">previous</button>
    <button (click)="submit()">submit</button>
  </mat-tab> 
  
</mat-tab-group>

TS:

changeIndex(tabgroup: MatTabGroup, number: number){
  tabgroup.selectedIndex = number;
}
  
submit(){ //Code for submitting}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.