简体   繁体   中英

How to call a function when a tab is selected in Angular 4 Tabs?

anyone knows how can I call a function when Tab 1 is selected ? md-on-select is no more working

<md-tab-group>
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>

template html:

 <md-tab-group (selectChange)='onSelectChange($event)'>
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>

component.ts

import {Component} from '@angular/core';


@Component({
  selector: 'tabs-overview-example',
  templateUrl: 'tabs-overview-example.html',
})
export class TabsOverviewExample {
  onSelectChange(event) {
    if(event.index== 0){
      console.log('Tab1 is selected!');
    }else{
      console.log('Tab1 is not selected!')
    }
  }
}

You need to use the selectChange event:

<md-tab-group (selectChange)="onTabSelectChange($event)">
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>

And in your component:

onTabSelectChange(tabChange: MdTabChangeEvent) {
 // do whatever you need to do here
}

You can review the docs for Material Tabs for more details on MdTabChangeEvent

You can do:

<md-tab-group #tabgroup (focusChange)="changeTab(tabgroup)">
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>

in ts file :

public changeTab(tabgroup) {
    let pid = tabgroup._currentLabelWrapper.id;     
    let activeTab =$("#"+pid).text().trim();
    console.dir("Active tab: " + activeTab);
}

This way you can have any number of tabs and instantly you can get which tab have been currently selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM