您如何从 Angular4 中的 bootstrap 选项卡集中获取选定的选项卡?

How do you get the selected tab from a bootstrap tabset in Angular4?

我有一组根据输入数据动态创建的选项卡。而我想要做的是能够弄清楚当前选择了哪个选项卡。在下面的示例代码中,我有一个选项卡控件,在所有这些控件下方,我有一个按钮,单击该按钮将删除所选选项卡。我尽量保持相对简单,它可能看起来做作,但我希望它能说明我的意思。

这是我的代码:

<div class="col-md-12">
  <ngb-tabset *ngIf="selectedInfo" type="groups" >
    <ngb-tab *ngFor="let tab of selectedInfo.groups" title={{tab.name}} >
        // some stuff in the tabs
    </ngb-tab>
  </ngb-tabset>
</div>

<div>
  <button class="btn btn-primary float-left" (click)="deleteTab()" > Delete Tab </button>
</div>


export class MyTabs implements OnInit {

  selectedIfno: MyInfoClass;

  ngOnInit(): void {

    // init data

  }

  deleteTab() {


  }

}

假设我想删除当前选中的标签页。我如何知道当前选择了哪个选项卡?

您可以获得 NgbTabset using Angular @ViewChild() to retrieve an instance of the the NgbTabset from the HTML. You'd then have access to the activeId in the class methods. Considering you are us *ngIf you may need to create a setter for @ViewChild() described in this 的活动标签页 ID (activeId)。我已将示例更新为使用 setter.

HTML:

<div class="col-md-12">
  <ngb-tabset #t="ngbTabset" *ngIf="selectedInfo" type="groups">
    <ngb-tab *ngFor="let tab of selectedInfo.groups" title={{tab.name}} >
        // some stuff in the tabs
    </ngb-tab>
  </ngb-tabset>
</div>

TS:

import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { NgbTabset } from '@ng-bootstrap/ng-bootstrap';

export class MyTabs implements OnInit {
  private tabSet: ViewContainerRef;

  @ViewChild(NgbTabset) set content(content: ViewContainerRef) {
    this.tabSet = content;
  };

  ngAfterViewInit() {
    console.log(this.tabSet.activeId);
  }

  deleteTab() {
    // currently selected tab id
    console.log(this.tabSet.activeId);
  }
}

这里是 plunker 功能演示。

我建议收听 tabChange 更改事件 - 这将允许您 "intercept" 活动页面更改的所有情况并存储有关当前所选选项卡的信息。这是想法的草图:

<ngb-tabset [activeId]="activeTab" (tabChange)="activeTab = $event.nextId"> ... </ngb-tabset>

还有一个工作的 plunker:http://plnkr.co/edit/4vRDHgWMhcvafXhQkxEO?p=preview

在输入答案时,我意识到跟踪活动选项卡 你自己 可能会有点麻烦,我们可以将此功能添加到选项卡集本身。欢迎在 https://github.com/ng-bootstrap/ng-bootstrap/issues

打开功能请求