【问题标题】:Validation not working after clear the form清除表格后验证不起作用
【发布时间】:2019-10-18 11:25:53
【问题描述】:

我无法使用 this.stockForm.reset() 清除;所以我在提交后使用它来清除数据:

 clearall(): void {
        this.isEditMode = false;
        this.stockForm.reset({
            sku: '',
            productName: '',
            counted: '',
        });
        Object.keys(this.stockForm.controls).forEach(key => {
            this.stockForm.get(key).setErrors(null);
        });
}

当我再次点击提交按钮时,我无法获得验证;获取默认值;所以让我知道如何在清除表单后再次验证。

【问题讨论】:

  • 为什么不能在表单上使用reset() 函数?
  • 您应该可以使用 typescript 中提供的 this.stockForm.reset() 函数。
  • @ng-suhas 同时使用在表单字段上显示触摸错误
  • 你有这方面的 stackblitz 吗?

标签: angular validation bootstrap-4 angular-reactive-forms


【解决方案1】:

你好,你就这样休息吧:

 clearall(): void {
        this.isEditMode = false;
        this.stockForm.reset();
        Object.keys(this.stockForm.controls).forEach(key => {
            this.stockForm.get(key).setErrors(null);
        });
     }

【讨论】:

  • 以上工作正常但我再次点击提交按钮需要显示验证但它没有发生?
  • 你为什么设置错误(null)?
【解决方案2】:

您可以在重置表单时尝试使用 Validators.required 吗?

clearall(): void {
        this.isEditMode = false;
        this.stockForm.reset({
            sku: ['', Validators.required],
            productName: ['', Validators.required],
            counted: ['', Validators.required],
        });
        Object.keys(this.stockForm.controls).forEach(key => {
            this.stockForm.get(key).setErrors(null);
        });
}

希望它有所帮助!干杯!

请检查这个例子 => https://stackblitz.com/edit/angular-reactive-forms-lgguij

【讨论】:

  • 我在上面写了同样的东西,但是重新点击提交按钮验证不起作用
  • 您能否在重置表单之前提及初始 formGroup ?
【解决方案3】:

重置表单后,您将通过调用 setErrors(null) 手动运行验证。 setErrors(null) 表示您将表单属性设置为有效,因此您不会收到任何验证消息。

setErrors

删除以下代码后即可使用

 Object.keys(this.stockForm.controls).forEach(key => {
        this.stockForm.get(key).setErrors(null);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-10
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多