import { Input, OnInit } from '@angular/core'; import { FormGroup, FormArray } from '@angular/forms'; import { buildFormControl } from './../../services/_formdata-utils'; export abstract class GroupInputComponent implements OnInit { @Input() control: FormGroup | FormArray; @Input() set meta(meta: StringMap) { this._meta = meta; this.exposeForTemplate(); this.updateFormGroupAndMeta(); }; formGoA: FormGroup | FormArray; childMetaArray: Array>; controlNames: Array; readonly componentName: string; exposeMetaInTemplate: string[] = []; _meta: StringMap ngOnInit() { this.updateFormGroupAndMeta(); } updateFormGroupAndMeta(): void { // Get the FormGroup or FormArray, and information about the controls inside it this.formGoA = this.control as FormGroup | FormArray; if (this.formGoA instanceof FormArray) { const meta = this._meta.meta; const formArrayLength = this.formGoA.length; let delta = meta.length - formArrayLength; while (delta > 0 && delta--) { this.formGoA.push(buildFormControl(meta[formArrayLength + delta])); } if (delta < 0) { this.formGoA.controls.length = meta.length; // Truncate the form array } } this.childMetaArray = Object.values(this._meta.meta); // Metadata array of all controls in group this.controlNames = Object.keys(this.formGoA.controls); } exposeForTemplate(): void { // Move meta variables up a level, for direct access in templates this.exposeMetaInTemplate.map(p => this[p] = this._meta[p] !== undefined ? this._meta[p] : this[p]); } getName(): string { return this.componentName; } }