0

I'm building an Angular 4 app with TypeScript and trying to add click event listeners to Material Design Tabs <md-tab> with no success.

I've tried different approaches but none of them seems to work.

Here is a simple HTML tabs example:

<md-tab-group>
    <md-tab label="Tab One">
        <p>Some content here</p>
    </md-tab>
    <md-tab label="Tab Two">
        <p>Some other content here</p>
    </md-tab>
</md-tab-group>

1. First Approach:

Material Design seems to generate the tab elements in the DOM dynamically, and giving the elements unique ids, so I've tried to target these ids in the TypeScript file constructor() function:

let tab1 = document.getElementById('md-tab-label-0-0');
let tab2 = document.getElementById('md-tab-label-0-1');

and add an eventListener() function to both properties:

tab1.addEventListener("click", () => {
    this.currentTab = 'my-first-tab';
});
tab2.addEventListener("click", () => {
    this.currentTab = 'my-second-tab';
});

but the problem is that tab1 and tab2 properties are returning null so this isn't working:

2. Second Approach:

I've tried to add a (click) binding to the HTML <md-tab> element:

<md-tab-group>
    <md-tab label="Tab One" (click)="checkActiveTab('my-first-tab')">
        <p>Some content here</p>
    </md-tab>
    <md-tab label="Tab Two" (click)="checkActiveTab('my-second-tab')">
        <p>Some other content here</p>
    </md-tab>
</md-tab-group>

in the TypeScript file I've initialized the returned value with the currentTab property, but the checkActiveTab() function is not triggering, so this isn't working either:

checkActiveTab(elem: string) {
    this.currentTab = elem;
}

Can anyone give me an idea of how can I do this? Basically, I would like to set the currentTab property based on the active tab.

Thanks in advance!

Csaba
  • 1,945
  • 3
  • 28
  • 46
  • 1
    Do you want to get what tab is selected? If so, you can just use `selectChange` *Output* of `md-tab-group`... ``... and in component do whatever do you want with `$event`. – developer033 Jun 11 '17 at 15:19
  • That's exactly what I was looking for! I was over complicating because didn't know about (selectChange) method. Thanks man! – Csaba Jun 11 '17 at 15:31
  • I just remembered I answered this question before :) – developer033 Jun 11 '17 at 15:32

0 Answers0