import { ApplicationRef , ComponentFactoryResolver , ComponentRef , EmbeddedViewRef , Injectable , Injector , Type , ViewContainerRef } from '@angular/core' ; import { LoggerService } from './logger.service' ; declare var $ ; export type ElementSelector = string | HTMLElement | JQuery < HTMLElement > ; @ Injectable ( { providedIn : 'root' } ) export class DomService { protected _name = 'DomService' ; constructor ( protected _componentFactoryResolver , protected _applicationRef , protected _injector , protected _loggerSvc ) { } protected getJQueryElement ( selector ) { return typeof selector === 'string' ? $ ( selector ) : $ ( selector ) ; } protected getComponentElement < T > ( componentRef ) { return ( componentRef . hostView as EmbeddedViewRef < any > ) . rootNodes [ 0 ] as HTMLElement ; } protected addComponent < T > ( componentType , elementExists , getParentElement ) { if ( elementExists ( ) ) { return ; } const factory = this . _componentFactoryResolver . resolveComponentFactory ( componentType ) ; const componentRef = factory . create ( this . _injector ) ; this . _applicationRef . attachView ( componentRef . hostView ) ; const parentElement = getParentElement ( ) ; const childElement = this . getComponentElement ( componentRef ) ; parentElement . append ( childElement ) ; componentRef . changeDetectorRef . detectChanges ( ) ; return componentRef ; } createChildComponent < T > ( componentType , componentSelector , parent ) { return this . addComponent ( componentType , ( ) => ! ! ( this . getJQueryElement ( componentSelector ) . length ) , ( ) => this . getJQueryElement ( parent ) ) ; } createComponent < T > ( componentType , viewContainerRef ) { if ( ! ! componentType && ! ! viewContainerRef ) { viewContainerRef . clear ( ) ; const factory = this . _componentFactoryResolver . resolveComponentFactory ( componentType ) ; const componentRef = viewContainerRef . createComponent ( factory ) ; return componentRef ; } } }