Making Material tabs scrollable

前端 未结 3 1370
长情又很酷
长情又很酷 2021-01-06 12:17

I\'m using Material tabs in my application (mat-tab s inside mat-tab-group) When there are more tabs than can be displayed, two navigation buttons

3条回答
  •  盖世英雄少女心
    2021-01-06 12:54

    Try my solution in this stackblitz demo.

    First get a reference to the matTabGroup:

    app.component.html

    
                   ^^^^^^^^^  
    

    app.component.ts

    @ViewChild('tabGroup')
    tabGroup;
    

    Then listen to the mouse scroll wheel event and trigger a custom scroll function:

    app.component.html

    
                            ^^^^^^^^^^^^^^^^^^  
    

    app.component.ts

    scrollTabs(event) {
      const children = this.tabGroup._tabHeader._elementRef.nativeElement.children;
    
      // get the tabGroup pagination buttons
      const back = children[0];
      const forward = children[2];
    
      // depending on scroll direction click forward or back
      if (event.deltaY > 0) {
        forward.click();
      } else {
        back.click();
      }
    }
    

    Disclaimer: This solution is very brittle. The Angular Material tabs do not offer an API for doing this. The solution depends on internal references that might change without notice (e. g. this private variable this.tabGroup._tabHeader). Also, it does not yet stop the page from scrolling and only works with vertical scrolling. (Those two can be addressed though.)

提交回复
热议问题