/** * The main component that renders single TabComponent * instances. */ import { AfterContentInit, Component, ContentChildren, EventEmitter, HostListener, Input, Output, QueryList, } from '@angular/core'; import {TabComponent} from './tab.component'; @Component({ selector: 'my-tabs', template: `
` }) export class TabsComponent implements AfterContentInit { public customClass: string; @ContentChildren(TabComponent) tabs: QueryList; @Output() public selectedActiveTab: EventEmitter = new EventEmitter(); @Input() offsetForSticky:number=0; @Input() isSticky:boolean; @Output() isStickyChange :EventEmitter = new EventEmitter(); public selected: string; disableScroll = false; @HostListener("window:scroll", []) onWindowScroll() { this.scroll(); } ngAfterContentInit() { if(this.tabs.length > 0) { this.selected = this.tabs.get(0).tabId; } } selectTab(tab: TabComponent, scroll=true){ this.unSelectTab(this.selected, tab.tabId); tab.active = true; this.selected = tab.tabId; this.selectedActiveTab.emit(tab.tabId); if(scroll) { this.disableScroll = true; setTimeout(() => { window.scrollTo({ top: document.getElementById(tab.tabId) ? document.getElementById(tab.tabId).offsetTop - (this.isSticky?250:180) : 250, behavior: 'smooth' }); setTimeout(() => { this.disableScroll = false; }, 600); }, 200); } } scroll(){ let tabDistanceFromCurrentViewTop = document.getElementById("main-tabs-div") ? document.getElementById("main-tabs-div").getBoundingClientRect().top : null; if((tabDistanceFromCurrentViewTop <= this.offsetForSticky)){ this.isStickyChange.emit(true); this.isSticky =true; }else if(!(tabDistanceFromCurrentViewTop <= this.offsetForSticky)){ this.isStickyChange.emit(false); this.isSticky =false; } if(this.disableScroll){ return; } // console.log(window.scrollY) let currentTabView = null; let windowInnerHeight = window && window.innerHeight ? window.innerHeight : 300; // console.log("find CT", windowInnerHeight) for (let tab of this.tabs) { let distanceFromCurrentViewTop = document.getElementById(tab.tabId) ? document.getElementById(tab.tabId).getBoundingClientRect().top : null; // console.log(pos, distanceFromCurrentViewTop, windowInnerHeight/2); if (distanceFromCurrentViewTop != null && distanceFromCurrentViewTop <= windowInnerHeight / 2) { currentTabView = tab; } else if (distanceFromCurrentViewTop != null && distanceFromCurrentViewTop > windowInnerHeight) { break; } } // console.log("current currentTabView", currentTabView.tabId) if (currentTabView && this.selected != currentTabView.tabId) { this.selectTab(currentTabView, false); this.disableScroll =true; setTimeout(() => { this.disableScroll = false; }, 600); } } unSelectTab(oldTabId, newTabId){ for (let tab of this.tabs) { if(tab.tabId == oldTabId){ tab.active = false; break; } } this.selected = newTabId; } }