2016-05-26 24 views
3

我想在angular2中的選項卡上設置活動類。我正在使用ng2-bootstrap插件作爲製表符,並且實際上不會讓用戶知道如何執行此操作。angular2在init上設置活動選項卡

從NG2的自舉的例子原創:

<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; 
} 

回答

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> 
+0

你快了4秒;)但是你的代碼中有一些錯誤。 'this.tabs..',如果你明確地想要最後一個,你可能希望密鑰是動態的。 – lexith

+0

謝謝指出那個詞法...我糾正了它.. – Som

+0

但你們兩個都沒有仔細閱讀這個問題,這不是OP所要求的。 – dfsq

1

起初,我明白你錯了,所以我更新了我的答案。 爲了讓你的榜樣靜態標籤,你有一個ID設置爲他們這樣的:

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

然後使用@ViewChild你可以得到它有一個屬性nativeElement這是probaby你想要的ElementRef的保持。

在你的組件,你必須從NG2的自舉導入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); 
    } 
} 

希望這會有所幫助。

+0

感謝您的答案。事實上,我需要訪問所有的選項卡。在我的示例中,我只使用靜態選項卡,並且我想要一個url參數來控制哪個選項卡處於活動狀態。 所以我想我會爲每個選項卡添加一個ID,然後嘗試訪問ViewChildren。 –

相關問題