Jidesh Vaidya
Jidesh Vaidya

Reputation: 23

how to change the angular tab using button in content?

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>

Upvotes: 2

Views: 5873

Answers (2)

Vostoros
Vostoros

Reputation: 11

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}

Upvotes: 1

Abhishek Kumar
Abhishek Kumar

Reputation: 2539

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

Upvotes: 2

Related Questions