// Form field row, capable of hosting any type of form field input compponent import { Component, ComponentFactoryResolver, Input, ViewChild, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; // import { ComponentHostDirective } from '@directives/component-host.directive'; // Group into barrel: https://basarat.gitbooks.io/typescript/docs/tips/barrel.html import { BasicinputComponent } from './../../fields/basicinput/basicinput.component'; import { DropdownModifiedInputComponent } from './../../fields/dropdown-modified-input/dropdown-modified-input.component'; import { CheckbuttonComponent } from './../../fields/checkbutton/checkbutton.component'; import { CheckbuttonGroupComponent } from './../../fields/checkbutton-group/checkbutton-group.component'; const validComponentsArray = [ BasicinputComponent, DropdownModifiedInputComponent, CheckbuttonComponent, CheckbuttonGroupComponent ]; const validComponents = validComponentsArray.reduce((acc, component) => Object.assign(acc, { [component.name]: component}), {}); type ValidComponentType = BasicinputComponent | DropdownModifiedInputComponent | CheckbuttonComponent | CheckbuttonGroupComponent; @Component({ selector: 'app-dynarow', templateUrl: './dynarow.component.html', styleUrls: ['./dynarow.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DynarowComponent), multi: true } ] }) export class DynarowComponent /* implements OnInit, ControlValueAccessor */ { /* @Input() meta; // TODO: Add type - will be a union type of all input types available - probably (?) // @ViewChild(ComponentHostDirective) // host: ComponentHostDirective; label: string; currentValue: string | boolean; propagateChange = (_: any) => {}; constructor(private componentFactoryResolver: ComponentFactoryResolver) { } ngOnInit() { this.label = this.meta.label; this.loadComponent(); } loadComponent() { let type = this.meta.type; console.log('Trying to load', type); const viewContainerRef = this.host.viewContainerRef; if (`${type}Component` in validComponents) { type = `${type}Component`; } if (type in validComponents) { // Create and insert the component const componentFactory = this.componentFactoryResolver.resolveComponentFactory(validComponents[type]); const componentRef = viewContainerRef.createComponent(componentFactory); (componentRef.instance).meta = this.meta; // TODO: Impove on by standardising interface console.dir(componentRef.instance); // Assign the FormControl, FormArry or FormGroup (componentRef.instance).formControlName = this.meta.name; (componentRef.instance).style = "outline: 5px red solid;"; } else { console.error('DYNAROW: Unknown Component Type'); } } public writeValue(value: any): void { // this.currentValue = (this.componentRef.instance).FormControl.value } public registerOnChange(fn: any): void { this.propagateChange = fn; } public registerOnTouched(fn: any): void {} */ }