group-input.component.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Input, OnInit } from '@angular/core';
  2. import { FormGroup, FormArray } from '@angular/forms';
  3. import { buildFormControl } from './../../services/_formdata-utils';
  4. export abstract class GroupInputComponent<C> implements OnInit {
  5. @Input()
  6. control: FormGroup | FormArray;
  7. @Input()
  8. set meta(meta: StringMap<any>) {
  9. this._meta = meta;
  10. this.exposeForTemplate();
  11. this.updateFormGroupAndMeta();
  12. };
  13. formGoA: FormGroup | FormArray;
  14. childMetaArray: Array<StringMap<any>>;
  15. controlNames: Array<string>;
  16. readonly componentName: string;
  17. exposeMetaInTemplate: string[] = [];
  18. _meta: StringMap<any>
  19. ngOnInit() {
  20. this.updateFormGroupAndMeta();
  21. }
  22. updateFormGroupAndMeta(): void {
  23. // Get the FormGroup or FormArray, and information about the controls inside it
  24. this.formGoA = this.control as FormGroup | FormArray;
  25. if (this.formGoA instanceof FormArray) {
  26. const meta = this._meta.meta;
  27. const formArrayLength = this.formGoA.length;
  28. let delta = meta.length - formArrayLength;
  29. while (delta > 0 && delta--) {
  30. this.formGoA.push(buildFormControl(meta[formArrayLength + delta]));
  31. }
  32. if (delta < 0) {
  33. this.formGoA.controls.length = meta.length; // Truncate the form array
  34. }
  35. }
  36. this.childMetaArray = Object.values(this._meta.meta); // Metadata array of all controls in group
  37. this.controlNames = Object.keys(this.formGoA.controls);
  38. }
  39. exposeForTemplate(): void {
  40. // Move meta variables up a level, for direct access in templates
  41. this.exposeMetaInTemplate.map(p => this[p] = this._meta[p] !== undefined ? this._meta[p] : this[p]);
  42. }
  43. getName(): string {
  44. return this.componentName;
  45. }
  46. }