检测当前活动选项卡上的单击. (“角度材料"选项卡) [英] Detect click on the currently active tab. ( Angular material tab )

查看:87
本文介绍了检测当前活动选项卡上的单击. (“角度材料"选项卡)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有不同标签的mat-tab组.我想检测活动标签标题上的单击.

I have a mat-tab group with different tabs. I want to detect click on the active tab header.

例如.我有2个选项卡-一个公司选项卡和一个用户选项卡,每个选项卡中都有2个视图-列表视图和详细视图.最初,我想加载列表,然后单击某个项目,然后转到相应项目的详细视图.但是,如果我再次单击选项卡标题,我想再次进入列表视图.

Eg. I have 2 tabs- a company tab and a users tab and inside each tab there are 2 views - a list view view and a detailed view. Initially I want to load the list and on clicking on an item, want to go to the corresponding item's detailed view. But If I click on the tab header again I want to goto the list view again.

像(selectedTabChange)这样的事件会检测选项卡是否已更改,但是由于我位于同一选项卡中,因此不会发出该事件.有帮助吗?

There are events like (selectedTabChange) which detects if tab is changed but since I am inside the same tab, it is not getting emitted. Any help.?

<mat-tab-group class="theme-specific-tabs account-page-tabs" [(selectedIndex)]="selectedTab"  (selectedIndexChange)="accountTabOnIndexChange($event)">

推荐答案

这是一个hack,但是应该可以使用.请注意,setTimeout()调用是必需的,因为选项卡的更改似乎发生在click事件到达回调之前,因此我们需要延迟保存选定的选项卡索引,直到click事件完成传播为止.这就是为什么我们不能简单地从MatTab检查活动标签索引的原因.

This is a hack, but it should work. Note that the setTimeout() call is necessary because it seems like the tab change happens before the click event gets to our callback, so we need to delay saving the selected tab index until the click event has completed propagation. That is also why we can't simply check for the active tab index from MatTab.

<mat-tab-group (selectedIndexChange)="selectedIndexChange($event)" (click)="tabClick($event)">
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>


selectedTabIndex: number = 0;
selectedIndexChange(index: number) {
  setTimeout(() => this.selectedTabIndex = index);
}

tabClick(event: MouseEvent) {
  let el = event.srcElement;
  const attr = el.attributes.getNamedItem('class');
  if (attr.value.indexOf('mat-tab-label-content') >= 0) {
    el = el.parentElement;
  }
  const tabIndex = el.id.substring(el.id.length - 1);
  if (parseInt(tabIndex) === this.selectedTabIndex) {
    // active tab clicked
    console.log(tabIndex);
  }
}

这是在stackblitz上.

这篇关于检测当前活动选项卡上的单击. (“角度材料"选项卡)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆