Search code examples
angularangular-materialangular7

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>

Solution

  • 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