angular2在init上设置活动选项卡

时间:2016-05-26 20:57:16

标签: angular

我正在尝试在angular2的选项卡上设置活动类。我正在使用ng2-bootstrap插件作为标签,并且实际上并没有解释如何操作。

来自ng2-bootstrap的原始示例:

<tabset>
    <tab heading="Static title">Static content</tab>
    <tab *ngFor="let tabz of tabs"
         [heading]="tabz.title"
         [active]="tabz.active"
         (select)="tabz.active = true"
         (deselect)="tabz.active = false"
         [disabled]="tabz.disabled"
         [removable]="tabz.removable"
         (removed)="removeTabHandler(tabz)">
      {{tabz?.content}}
    </tab>
    <tab (select)="alertMe()">
      <template tabHeading>
        <i class="glyphicon glyphicon-bell"></i> Alert!
      </template>
      I've got an HTML heading, and a select callback. Pretty cool!
    </tab>
  </tabset>

因此,如果我想将最后一个标签设置为加载时处于活动状态,如何在打字稿中访问此标签?主要问题是我只能访问在typescript本身创建的选项卡,而不能访问静态选项卡,如第一个或最后一个。

我喜欢这样的事情:

ngOnActivate() {
    tab[4].activ=true;
}

4 个答案:

答案 0 :(得分:2)

起初,我理解你错了,所以我更新了我的答案。 要获取示例中的静态选项卡,您必须像这样设置ID:

<tabset>
    <tab #headingTab heading="Static title">Static content</tab>
     ...

然后使用@ViewChild,您可以抓住ElementRef,其中有nativeElement属性,这可能是您想要的。

在你的组件中,你必须从ng2-bootstrap导入TabsetComponent

...
import {TAB_DIRECTIVES, TabsetComponent} from "ng2-bootstrap/ng2-bootstrap";
...

要访问它,您必须挂钩ngAfterViewInit()生命周期钩子,因此您必须导入AfterViewInit并实现它:

export class MyComponent implements AfterViewInit {

    @ViewChild('headingTab')       // id of the tab in your html template
    private _headingTab:TabsetComponent;  // followed by a variable which will hold the component

     ngAfterViewInit():any {
         console.log(this._headingTab);
     }
}

希望这有帮助。

答案 1 :(得分:0)

试试这个:

<tab (select)="alertMe()" [ngClass]="{active: last}">
      <template tabHeading>
        <i class="glyphicon glyphicon-bell"></i> Alert!
      </template>
      I've got an HTML heading, and a select callback. Pretty cool!
 </tab>

答案 2 :(得分:0)

在使用ngx-bootstrap TabsControl的Angular 5应用程序中,我具有静态选项卡,并且需要根据可观察到的调用的结果来设置活动选项卡,该调用是在ngOnInit函数中进行的。对我来说,我的代码正在执行以下操作:

首先将整个标签集放入ngx-bootstrap的TabsetComponent中:

@ViewChild(TabsetComponent)
tabSet: TabsetComponent;

然后在可观察对象的订阅成功操作中(当我知道要选择的选项卡时):

if (showMessageTab) {
    this.tabSet.tabs[4].active = true;
} else {
    this.tabSet.tabs[0].active = true;
}

我遇到的另一件事是和,这些项目不能使用ngIf或其他角度属性后期加载。在我的实验中,为了使angular能够填充ViewChild元素,看来它们必须在第一次加载时就位于html中。这对您可能已经很明显了,但是我碰到它时就把它扔了。

我希望这可以帮助某人。

答案 3 :(得分:0)

你可以在模板中这样做

<tabset>
  <tab [active]="currentTabId === 0">Tab1 Content<tab>
  <tab [active]="currentTabId === 1">Tab2 Content<tab>
  <tab [active]="currentTabId === 2">Tab3 Content<tab>
</tabset>

并在打字稿中添加

currentTabId = 1
相关问题