jlf-typed-form-craft
Version:
A library to create forms with typed datas and validations
34 lines (33 loc) • 1.81 kB
TypeScript
import { FormControl, FormGroup } from '@angular/forms';
import 'reflect-metadata';
export interface FormControlOptions<T = any> {
validators?: any[];
asyncValidators?: any[];
defaultValue?: T;
disable?: (form: FormGroup) => boolean;
}
export declare const controlProp: (options: FormControlOptions) => (target: any, propertyKey: string) => void;
export type FormGroupControls<T> = {
[K in keyof T]?: 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>;