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