• Reordering & hiding tabs in angular 2 using QueryList

    736 Views Asked by At

    There are 2 tabs (TabA and TabB) resulting from the TabsComponent below.

    @Component({
      selector: 'tabs',
      template:
      `
            <ul class="tab-nav">
                <li *ngFor="let tab of tabs" (click)="selectTab(tab)" [class.active]="tab.active">
                    {{tab.title}} 
                </li>
            </ul>
            <ng-content></ng-content>
        `
    })
    export class TabsComponent implements AfterContentInit {
      @ContentChildren(TabComponent) tabs: QueryList<TabComponent>;
      ngAfterContentInit() {
        let activeTabs = this.tabs.filter((tab) => tab.active);
        if (activeTabs.length === 0) {
          this.selectTab(this.tabs.first);
        }
      }
      selectTab(tab: TabComponent) {
        this.tabs.toArray().forEach(tab => tab.active = false);
        tab.active = true;
        this.onTabSelect.emit(tab);
      }
    }
    
    @Component({
        selector: 'tab',
        template:
        `
            <div class="tab-content">
               <ng-content></ng-content>
            </div>
        `
    })
    export class TabComponent {
        @Input('tabTitle') title: string;
        @Input() active = false;    
    }
    

    There are three tab selection scenarios driven by radios: 1) Display both tabs with TabA selected by default 2) Display TabA when link A was clicked, Tab B should be hidden 3) Display TabB when link B was clicked, Tab A should be hidden

    As tabs are contained in QueryList, there are no methods that can reorder/sort the tab. Also tried converting QueryList toArray and then sort it by the selected tab it did not work.

    Would appreciate your guidance.

    0

    There are 0 best solutions below