1.1.0 • Published 8 months ago

lit-ng-form v1.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
8 months ago

LIT FORM NG

A Lit Element library to semplify the use of forms in the Angular way.

Introduction

Working with forms can be a very tedious task of our work. Even the simplest application can quickly become overwhelming, causing us to lose control over the communication flow between states and events. If you are familiar with Angular forms, then you'll be just fine.

Features

  • FormArray | FormGroup | FormControl
  • Two Way Bindings
  • Async Validators and Custom Async Validators

Future implementations

  • FormBuilder
  • Custom Accessors

Note

Since each control (FormGroup | FormArray | FormControl) extend an AbstractControl, they share the same properties and methods.

Properties

AttributeTypeDescription
parentAbstractControl | nullreadonly The parent control.
valueanyreadonly FormGroup An object with a key-value pair for each member control (if not disabled) of the group.
Arrayreadonly FormArray An array of values for each member control (if not disabled).
anyreadonly FormControl The current value.
valueChangesObservablereadonly An observable that emits an event every time the value of the control changes
statusChangesObservablereadonly An observable that emits an event every time the status of the control changes
disabledChangesObservableTODO
errorsValidationErrors | nullreadonly An object containing any errors generated by failing validation, or null if there are no errors.
updateOnFormHooksreadonly Reports the update strategy of the AbstractControl (meaning the event on which the control updates itself). Possible values: 'change' | 'blur' Default value: 'change'
statusFormControlStatusreadonly The validation status of the control.
validbooleanreadonly A control is valid when its status is VALID.
invalidbooleanreadonly A control is invalid when its status is INVALID.
pendingbooleanreadonly A control is pending when its status is PENDING.
disabledbooleanreadonly A control is disabled when its status is DISABLED.
enabledbooleanreadonly A control is enabled as long as its status is not DISABLED.
touchedbooleanreadonly A control is marked touched once the user has triggered a blur event on it.
untouchedbooleanreadonly A control is untouched if the user has not yet triggered a blur event on it.
pristinebooleanreadonly A control is pristine if the user has not yet changed the value in the UI.
dirtybooleanreadonly A control is dirty if the user has changed the value in the UI.

Properties (FormGroup)

AttributeTypeDescription
controlsanyA collection of child controls. The key for each child is the name under which it is registered.

Properties (FormArray)

AttributeTypeDescription
controlsArrayAn array of child controls.
lengthnumberLength of the control array.

Properties (FormControl)

AttributeTypeDescription
defaultValueanyreadonly The default value of this FormControl, used whenever the control is reset without an explicit value.

Methods

MethodDescription
setValue(value, options)FormGroup: Sets the value of the FormGroup. It accepts an object that matches the structure of the group, with control names as keys.
FormArray: Sets the value of the FormArray. It accepts an array that matches the structure of the control.
FormControl: Sets a new value for the form control.
getRawValue()FormGroup: The aggregate value of the FormGroup, including any disabled controls.
FormArray: The aggregate value of the array, including any disabled controls.
FormControl: For a simple FormControl, the raw value is equivalent to the value.
patchValue(value, options)FormGroup: Patches the value of the FormGroup. It accepts an object with control names as keys.
FormArray: Patches the value of the FormArray. It accepts an array that matches the structure of the control.
FormControl: Patches the value of a control.
setParent(control)Sets the parent of the control.
disable(options)Disables the control. This means the control is exempt from validation checks and excluded from the aggregate value of any parent. Its status is DISABLED.
enable(options)Enables the control. This means the control is included in validation checks and the aggregate value of its parent. Its status recalculates based on its value and its validators.
reset(value, options)FormGroup: Resets the FormGroup, marks all descendants as pristine and untouched and sets the value of all descendants to their default values, or null if no defaults were provided.
FormArray: Resets the FormArray, marks all descendants as pristine and untouched and sets the value of all descendants to their default values, or null if no defaults were provided.
FormControl: Resets the form control, marking it pristine and untouched, and resetting the value. The new value will be the provided value (if passed), null, or the initial value if nonNullable was set in the constructor via FormControlOptions.
updateValueAndValidity()Updates the value and validity status of the control. By default, it also updates the value and validity of its ancestors.
setValidators(validators)Sets the synchronous validators that are active on this control. Calling this overwrites any existing synchronous validators.
addValidators(validators)Add a synchronous validator or validators to this control, without affecting other validators.
setAsyncValidators(validators)Sets the asynchronous validators that are active on this control. Calling this overwrites any existing asynchronous validators.
addAsyncValidators(validators)Add a synchronous validator or validators to this control, without affecting other validators.
setErrors(errors, options)Sets errors on a form control when running validations manually, rather than automatically.
get(path)Retrieves a child control given the control's name or path.
markAllAsTouched()Marks the control and all its descendant controls as touched.
markAsTouched(options)Marks the control as touched. A control is touched by focus and blur events that do not change the value.
markAsUntouched(options)Marks the control as untouched.
markAsDirty(options)Marks the control as dirty. A control becomes dirty when the control's value is changed through the UI; compare markAsTouched.
markAsPristine(options)Marks the control as pristine.
markAsPending()TODO Marks the control as pending.

Methods (FormArray)

MethodDescription
at(index)Get the AbstractControl at the given index in the array.
push(control, options)Insert a new AbstractControl at the end of the array.
insert(index, control, options)Insert a new AbstractControl at the given index in the array.
removeAt(index, options)Remove the control at the given index in the array.
setControl(index, control, options)Replace an existing control.
clear(index, control, options)Remove all controls in the FormArray.

How to use

@customElement('my-form')
export class MyForm extends LitElement {

    private form: FormGroup = new FormGroup(this, {
        name: new FormControl(this, 'Carlo', [ Validators.required ]),
        age: new FormControl(this, 34, [ Validators.required ]),
    });

    private onSubmit(event: Event): void {
        event.preventDefault();
        if (this.form.invalid) return;
        console.log(this.form.value);
    }

    protected render(): TemplateResult {
        return html`
            <form @submit="${this.onSubmit}">
                <div>
                    <label>Name:</label>
                    <input type="text" ${this.form.connect('name')}>
                    ${this.form.get('name')?.errors?.required ? html`<small>Required field</small>` : html``}
                </div>
                <div>
                    <label>Age:</label>
                    <input type="number" ${this.form.connect('age')}>
                    ${this.form.get('age')?.errors?.required ? html`<small>Required field</small>` : html``}
                </div>
                <button type="submit" ?disabled="${this.form.invalid}">SUBMIT</button>
            </form>
        `;
    }

}
1.1.0

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago