import { Component , ComponentFactory , ComponentFactoryResolver , ComponentRef , EventEmitter , Input , OnChanges , OnDestroy , OnInit , Output , SimpleChanges , ViewChild , ViewContainerRef } from '@angular/core' ; import { CsvConfigComponent } from './csv-config/csv-config.component' ; import { JsonConfigComponent } from './json-config/json-config.component' ; import { FileConfig } from './file-config' ; import { ImportService } from '../../import.service' ; import { Subscription } from 'rxjs' ; import { FormGroup } from '@angular/forms' ; export const configComponents = { json : JsonConfigComponent , csv : CsvConfigComponent } ; @ Component ( { selector : 'cmdb-file-config' , templateUrl : './file-config.component.html' , styleUrls : [ './file-config.component.scss' ] } ) export class FileConfigComponent extends FileConfig implements OnInit , OnChanges , OnDestroy { @ ViewChild ( 'fileConfig' , { read : ViewContainerRef , static : true } ) fileConfig ; @ Input ( ) fileFormat : string = 'json' ; @ Output ( ) public configChange : EventEmitter < any > ; private configChangeSubscription : Subscription ; private component : any ; public componentRef : ComponentRef < any > ; private currentFactory : ComponentFactory < any > ; constructor ( private resolver , private importService ) { super ( ) ; this . configChange = new EventEmitter < any > ( ) ; this . configChangeSubscription = new Subscription ( ) ; } public ngOnInit ( ) { this . resetConfigSub ( ) ; this . fileConfig . clear ( ) ; } private resetConfigSub ( ) { this . configChangeSubscription = this . configForm . valueChanges . subscribe ( ( ) => { this . configChange . emit ( this . configForm . getRawValue ( ) ) ; } ) ; } public ngOnChanges ( changes ) { if ( changes . fileFormat !== undefined && ( changes . fileFormat . currentValue !== undefined || changes . fileFormat . currentValue !== '' ) && changes . fileFormat . firstChange === false ) { this . fileConfig . clear ( ) ; this . configForm = new FormGroup ( { } ) ; this . resetConfigSub ( ) ; this . component = configComponents [ this . fileFormat ] ; this . currentFactory = this . resolver . resolveComponentFactory ( this . component ) ; this . importService . getObjectParserDefaultConfig ( this . fileFormat ) . subscribe ( defaultParserConfig => { this . defaultParserConfig = defaultParserConfig ; this . componentRef = this . fileConfig . createComponent ( this . currentFactory ) ; this . componentRef . instance . configForm = this . configForm ; this . componentRef . instance . defaultParserConfig = this . defaultParserConfig ; } ) ; } } public ngOnDestroy ( ) { this . configChangeSubscription . unsubscribe ( ) ; } }