Angular2 - 重置时反应形式抛出错误

时间:2017-07-25 00:21:32

标签: angular typescript

我有一个带有自定义验证器的反应式表单设置。我有一个方法可以重置表单,但我想在发生这种情况时,它会弄乱验证器并抛出错误。

组件:

/**
 * 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();
}

在我的HTML中,我正在调用reset方法:

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

重置表单后,我收到错误ERROR TypeError: Cannot read property 'length' of null

通过在现有表单上调用该方法,还有更多的重置比我假设的那样吗?

2 个答案:

答案 0 :(得分:3)

复位还有更多。

FormGroup.reset的签名是

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

您可以看到第一个参数是表单将重置的表单组的所需值,它的默认值为{},这意味着在您的情况下,表单值将为{{ 1}},而你需要的是所有的子数组。在您的情况下重置表单的正确方法是:

{}

答案 1 :(得分:0)

您应该将初始状态对象传递给reset方法,以便不使用null初始化控件。您可以在renderForm方法中重用传递给group方法的对象。 有关详细信息,请参阅https://angular.io/guide/reactive-forms#reset-the-form-flags