0
我已經創建了一個工作正常的標籤組件。我想以編程方式支持更改標籤,但我不確定如何去做。Angular 2動態改變標籤
這裏的
@Component({
selector: 'tabs',
template: `
<ul>
<li *ngFor="let tab of tabsMenu" (click)="tabClick(tab)" [class.active]="tab.index === activeTabIndex">
{{ tab.title }}
</li>
</ul>
<div>
<ng-content select="tab-content"></ng-content>
</div>
`
})
export class TabsComponent implements AfterViewInit {
@Input() tabsMenu: MenuItem[];
@Input() activeTabIndex: number = 0;
@ContentChildren(TabContentComponent) tabsContent: QueryList<TabContentComponent>;
private tabsContentComponents: TabContentComponent[] = [];
ngAfterViewInit() {
this.tabsContentComponents = this.tabsContent.toArray();
this.setActiveTab(this.activeTabIndex);
}
tabClick(tab: MenuItem) {
this.activeTabIndex = tab.index;
this.setActiveTab(tab.index);
}
private setActiveTab(index: number) {
this.tabsContentComponents.filter((temp) => {
temp.activeTabIndex = this.activeTabIndex;
});
}
}
標籤內容組件
@Component({
selector: 'tab-content',
template: `
<div [hidden]="tabIndex !== activeTabIndex">
<ng-content></ng-content>
</div>
`
})
export class TabContentComponent {
@Input() tabIndex: number;
activeTabIndex: number = 0;
}
的代碼示例中使用是我到目前爲止的代碼...
卡組件
@Component({
selector: 'example',
template: `
<tabs [tabsMenu]="tabs">
<tab-content>
Tab 1
</tab-content>
<tab-content>
Tab 2
</tab-content>
<tab-content>
Tab 3
</tab-content>
</tabs>
`
})
export class TabContentComponent {
tabs: MenuItem[] = [
new MenuItem(0, 'Tab 1'),
new MenuItem(1, 'Tab 2'),
new MenuItem(2, 'Tab 3')
];
}
我現在要做的是在tab-content
組件中有一個按鈕,該按鈕將重定向到另一個選項卡。我不完全確定如何更改TabComponent
中的activeTabIndex
以便能夠訪問不同的選項卡。
感謝您的回答,解決方案奏效! :)我知道材料組件,它們看起來很棒:)它只是這個特定的項目有很多自定義樣式等等,所以我想我會自己做 –
Yw!是的,我的觀點更多地是關於查看代碼本身。 :)使用通常也是一個好主意。 =) – mxii