UNPKG

jlf-typed-form-craft

Version:
27 lines (26 loc) 1.59 kB
import { FormControl, FormGroup } from '@angular/forms'; import 'reflect-metadata'; export type FormGroupControls<T> = { [K in keyof T]?: T[K] extends object ? FormGroup<FormGroupControls<T[K]>> : FormControl<T[K]>; }; export interface DestroyableFormGroup<T> extends FormGroup<FormGroupControls<T>> { destroy: () => void; } /** * Creates a `DestroyableFormGroup` instance from a given class instance, using metadata to configure form controls and * validators. It maps the class instance's properties to form controls, applying default values, synchronous validators, * asynchronous validators, and enable/disable conditions where applicable. * * @template T The type of the class instance used for creating the form. * @param {T} instance An object instance of the class for which form controls should be created. * @returns {DestroyableFormGroup<T>} A reactive form group enhanced with a `destroy` method for cleanup. * * The method extracts metadata from the class instance to dynamically configure the form: * - Metadata specifies form control values, validators, and conditions for enabling or disabling controls. * - Validators and async validators are applied after the form group is created. * - The enable/disable logic listens to form changes and adjusts controls dynamically. * * The returned `DestroyableFormGroup` includes a `destroy` method, which unsubscribes from any internal subscriptions, * ensuring proper resource cleanup. */ export declare const createFormFromClass: <T extends Record<string, any>>(instance: T) => DestroyableFormGroup<T>;