Created
September 28, 2017 15:30
-
-
Save rendfall/4ec9367a82ea0d6bb945a0265a9f7425 to your computer and use it in GitHub Desktop.
Angular 2+ tabsComponent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AfterContentInit, Component, Input, OnChanges, SimpleChanges } from '@angular/core'; | |
interface TabInterface{ | |
active: boolean; | |
name: string | |
} | |
@Component({ | |
selector: 'app-tab', | |
template: `<div class="tab" [hidden]="!active"><ng-content></ng-content></div>`, | |
styles: [`.tab { width: 100%; height: 100% }`] | |
}) | |
export class TabComponent { | |
public active = false; | |
@Input() name: string; | |
constructor( | |
private tabsComponent: TabsComponent | |
) {} | |
ngOnInit() { | |
this.tabsComponent.addTab(this); | |
} | |
} | |
@Component({ | |
selector: 'app-tabs', | |
template: `<ng-content></ng-content>`, | |
styles: [] | |
}) | |
export class TabsComponent implements OnChanges, AfterContentInit { | |
@Input() selected: string; | |
public tabs: Array<TabInterface> = []; | |
public ngOnChanges(changes: SimpleChanges) { | |
let { selected } = changes; | |
if (selected && selected.currentValue) { | |
this.selectTab(selected.currentValue); | |
} | |
} | |
public ngAfterContentInit() { | |
this.selectTab(this.selected); | |
} | |
public get count() { | |
return this.tabs.length; | |
} | |
public addTab(tab: any) { | |
if (this.tabs.length === 0) { | |
tab.active = true; | |
} | |
this.tabs.push(tab); | |
} | |
private deselectAll() { | |
this.tabs.map((t) => t.active = false); | |
} | |
private selectTab(name: string) { | |
this.deselectAll(); | |
let selected = this.tabs.find(t => t.name === name); | |
if (selected) { | |
selected.active = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment