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

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

问题描述

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

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

例如.我有 2 个选项卡 - company 选项卡users 选项卡,每个选项卡内有 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() 调用是必要的,因为似乎选项卡更改发生在单击事件到达我们的回调之前,因此我们需要延迟保存所选选项卡索引,直到单击事件完成传播.这也是我们不能简单地从 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天全站免登陆