How to get the active tab In Angular Material2

后端 未结 4 385
不思量自难忘°
不思量自难忘° 2020-12-05 02:13

I want to get which tab is active. I tried to use a @ViewChild decorator and accessing the element properties that way, but it returns null.

<
4条回答
  •  半阙折子戏
    2020-12-05 02:36

    Well, I'm not sure if I understood well your question because, by default the index always starts counting from zero unless you set manually the [selectedIndex] property.

    Anyway, if you really want to see which tab is selected on initialization you could implement the AfterViewInit interface and do the following:

    export class AppComponent implements AfterViewInit, OnInit {
    
    ...
    
      ngAfterViewInit() {
        console.log('afterViewInit => ', this.tabGroup.selectedIndex);
      }
    }
    

    On other hand, if you want to check which tab is selected based on changes (what makes more sense), here you go:

    HTML:

    
      Content 1
      Content 2
    
    

    Component:

    tabChanged(tabChangeEvent: MatTabChangeEvent): void {
      console.log('tabChangeEvent => ', tabChangeEvent);
      console.log('index => ', tabChangeEvent.index);
    }
    

    DEMO

提交回复
热议问题