import { ApplicationRef , ComponentFactoryResolver , ComponentRef , Inject , Injectable , Injector } from '@angular/core' ; import { LightboxComponent } from './lightbox.component' ; import { LightboxConfig } from './lightbox-config.service' ; import { LightboxEvent , LIGHTBOX_EVENT , IAlbum } from './lightbox-event.service' ; import { LightboxOverlayComponent } from './lightbox-overlay.component' ; import { DOCUMENT } from '@angular/common' ; @ Injectable ( ) export class Lightbox { constructor ( private _componentFactoryResolver , private _injector , private _applicationRef , private _lightboxConfig , private _lightboxEvent , @ Inject ( DOCUMENT ) private _documentRef ) { } open ( album , curIndex = 0 , options = { } ) { const overlayComponentRef = this . _createComponent ( LightboxOverlayComponent ) ; const componentRef = this . _createComponent ( LightboxComponent ) ; const newOptions = { } ; this . _lightboxEvent . broadcastLightboxEvent ( { id : LIGHTBOX_EVENT . OPEN } ) ; Object . assign ( newOptions , this . _lightboxConfig , options ) ; componentRef . instance . album = album ; componentRef . instance . currentImageIndex = curIndex ; componentRef . instance . options = newOptions ; componentRef . instance . cmpRef = componentRef ; overlayComponentRef . instance . options = newOptions ; overlayComponentRef . instance . cmpRef = overlayComponentRef ; setTimeout ( ( ) => { this . _applicationRef . attachView ( overlayComponentRef . hostView ) ; this . _applicationRef . attachView ( componentRef . hostView ) ; overlayComponentRef . onDestroy ( ( ) => { this . _applicationRef . detachView ( overlayComponentRef . hostView ) ; } ) ; componentRef . onDestroy ( ( ) => { this . _applicationRef . detachView ( componentRef . hostView ) ; } ) ; const containerElement = newOptions . containerElementResolver ( this . _documentRef ) ; containerElement . appendChild ( overlayComponentRef . location . nativeElement ) ; containerElement . appendChild ( componentRef . location . nativeElement ) ; } ) ; } close ( ) { if ( this . _lightboxEvent ) { this . _lightboxEvent . broadcastLightboxEvent ( { id : LIGHTBOX_EVENT . CLOSE } ) ; } } _createComponent ( ComponentClass ) { const factory = this . _componentFactoryResolver . resolveComponentFactory ( ComponentClass ) ; const component = factory . create ( this . _injector ) ; return component ; } }