【问题标题】:How to prevent tab selection on ngx-bootstrap如何防止在 ngx-bootstrap 上选择选项卡
【发布时间】:2018-02-05 15:51:13
【问题描述】:

我有两个带有 ngx-bootstrap 的选项卡,如下所示,我想以编程方式停止选项卡功能的工作:

<tabset>
    <tab heading="First">Tab 1 content</tab>
    <tab heading="Second">Tab 2 content</tab>
</tabset>

<label>Edit in progress: </label>
<input type="checkbox" [(ngModel)]="isTabSwitchEnabled">

基本上,如果我在 Tab 1 中有一个脏表格,我想弹出一个“放弃更改?”允许用户“导航”到 Tab 2 之前的对话框。我在 ngx-bootstrap tabs API 上看不到我可以使用的任何东西。

我有一个示例Stackblitz,我尝试在标签上使用[disabled],它可以部分工作,但不能完全工作,因为我无法以编程方式将标签设置为活动状态(或者我不知道如何):

export class MyComponent  {
  disableSwitching: boolean;
  @ViewChild('tabset') tabset: TabsetComponent;
  @ViewChild('first') first: TabDirective;
  @ViewChild('second') second: TabDirective;

  confirmTabSwitch($event) {
    if (this.disableSwitching) {
      const confirm = window.confirm('Discard changes and switch tab?');
      if (confirm) {
        this.disableSwitching = false;
        this.second.active = true;
      }
    }
  }

}

this.second.active = true 不会切换到新标签,只会将其标记为活动状态。如果我尝试使用 this.tabset.tabs[index].active = true; 也是一样。

有没有办法拥有这个功能?启用和禁用切换标签?理想情况下也将它绑定到路由器(但我肯定需要编程访问)。

【问题讨论】:

    标签: angular twitter-bootstrap tabs ngx-bootstrap


    【解决方案1】:

    这是一个有效的 stackblitz 示例 - https://stackblitz.com/edit/ngx-bootstrap-tabs-rs832l?file=app/app.component.ts

    这里的事情是select 事件在选项卡集将所有其他选项卡的active 属性设置为false 之前发出,因此您需要将选择选项卡的代码包装在setTimeout 或类似的东西中。这将在标签集的所有内部操作之后设置活动标签。

    编辑:正如 OP 所说,目前 (ngx-bootstrap@2.0.2) 的解决方法是在 tabset 组件上找到匹配的元素并激活:

    confirmTabSwitch($event) {
      if (this.disableSwitching) {
        const confirm = window.confirm('Discard changes and switch tab?');
        if (confirm) {
          this.disableSwitching = false;
          const liArr = Array.from(this.tabsetEl.nativeElement.querySelectorAll('ul li'));
          let tabIndex;
          liArr.forEach((li, i) => {
            if(li.contains($event.target)) {
              tabIndex = i;
            }
          });
          setTimeout(() => this.tabset.tabs[tabIndex].active = true);
        }
      }
    }
    

    【讨论】:

    • 谢谢。知道这有点有用,但我仍然对这个演示有一点问题:单击选项卡 2。然后选中复选框。然后再次单击选项卡 1,并单击“确定”确认。它不会切换回 1。
    • 下面的示例中有一个硬代码,仅用于演示目的。它的动态版本看起来有点像 stackblitz.com/edit/ngx-bootstrap-tabs-dfvqln?file=app/… 。这个实现很混乱,但它可以作为一种解决方法。我们将在未来的版本中提供一个 API 来防止选项卡选择。
    【解决方案2】:

    这里的问题是:

    @ViewChild('first') first: TabDirective;
    

    不指向 TabDirective 而只是原生 ElementRef ,所以 this.second.active = true; 不会使 TabDirective 处于活动状态。

    您只需使用this.tabset.tabs[index].active = true;即可实现这一目标

    WORKING DEMO

    【讨论】:

    • 谢谢,但我没有使用 ElementRef,您可以检查问题中的代码和链接的 Stackblitz。此外,您的工作演示链接不起作用。
    • 是的,我知道,但有些方法,如果你检查它返回 ElementRef 而不是 TabDirective ,因为该活动代码不起作用。
    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多