import { Directive , ElementRef , QueryList , ContentChildren , Input , AfterContentInit , ViewContainerRef , OnChanges , SimpleChanges } from '@angular/core' ; import { ResizeService } from '../resize/index' ; import { LayoutSwitcherItemDirective } from './layout-switcher-item.directive' ; @ Directive ( { selector : '[uxLayoutSwitcher]' } ) export class LayoutSwitcherDirective implements AfterContentInit , OnChanges { @ Input ( ) group : string ; @ ContentChildren ( LayoutSwitcherItemDirective ) private _layouts : QueryList < LayoutSwitcherItemDirective > ; private _width : number ; private _activeLayout : LayoutSwitcherItemDirective ; constructor ( private _elementRef , resizeService , private _viewContainerRef ) { resizeService . addResizeListener ( _elementRef . nativeElement ) . subscribe ( event => { this . _width = event . width ; this . updateActiveLayout ( ) ; } ) ; } ngOnChanges ( changes ) { if ( changes . group . currentValue !== changes . group . previousValue ) { this . updateActiveLayout ( ) ; } } getActiveLayout ( ) { if ( ! this . _layouts ) { return null ; } return this . _layouts . filter ( layout => this . group === layout . getConfig ( ) . group ) . find ( layout => { const minWidth = layout . getConfig ( ) . minWidth || 0 ; const maxWidth = layout . getConfig ( ) . maxWidth || Infinity ; return this . _width >= minWidth && this . _width < maxWidth ; } ) ; } updateActiveLayout ( ) { const layout = this . getActiveLayout ( ) ; if ( this . _activeLayout === layout ) { return ; } if ( this . _activeLayout ) { this . _activeLayout . deactivate ( ) ; } this . _activeLayout = layout ; if ( this . _activeLayout ) { this . _activeLayout . activate ( ) ; } } ngAfterContentInit ( ) { this . _width = this . _elementRef . nativeElement . offsetWidth ; requestAnimationFrame ( this . updateActiveLayout . bind ( this ) ) ; } }