2
votes

I have a reactive form setup with a custom validator. I have a method which is supposed to reset the form but I think upon this happening, it is messing with the validator and throwing an error.

Component:

/**
 * Render the form in the UI to allow
 *
 * @memberof FilterSearchComponent
 */
renderForm() {
    this.importForm = this.fb.group({
        area: [[]],
        silo: [[]],
        department: [[]],
        location: [[]],
        segment: [[]],
        role: [[]]
    },
    {
        validator: (formGroup: FormGroup) => {
            return this.validateFilter(formGroup);
        }
    });
}

/**
 * Checks to see that at least one of the filter
 * options have been filled out prior to searching
 * for employees.
 *
 * @param formGroup
 */
validateFilter(formgroup: FormGroup) {
    if (formgroup.controls["area"].value.length ||
        formgroup.controls["silo"].value.length ||
        formgroup.controls["department"].value.length ||
        formgroup.controls["location"].value.length ||
        formgroup.controls["segment"].value.length ||
        formgroup.controls["role"].value.length
    ) {
        return null;
    } else {
        return { noFilterOptions: true };
    }
}

/**
 * On the resetting of the filter search,
 * clear our fields that were filled out.
 *
 * @param {any} data
 * @memberof FilterSearchComponent
 */
onReset(data) {
    this.importForm.reset();
}

In my HTML, I am calling the reset method like so:

(click)="onReset(importForm.value)"

Upon resetting my form, I am given the error that ERROR TypeError: Cannot read property 'length' of null.

Is there more to the reset than I am assuming by just calling that method on the existing form?

2

2 Answers

3
votes

There is more to the reset than that.

The signature of FormGroup.reset is

reset(value: any = {}, options: {onlySelf?: boolean, emitEvent?: boolean} = {}).

You can see that the first parameter is the desired value of the form group to which the form will reset, and it has default value of {}, which means in your case, the form value will be {}, while your need are all the sub arrays. The correct way to reset the form in your case is:

this.importForm.reset({
  area: [],
  silo: [],
  department: [],
  location: [],
  segment: [],
  role: []
});
0
votes

You should pass an initial state object to the reset method, so that your controls are not initialized with null. You could reuse the object that you pass into the group method in your renderForm method. See https://angular.io/guide/reactive-forms#reset-the-form-flags for more information.