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!