【问题标题】:How to reset form validation on submission of the form in ANGULAR 2如何在 ANGULAR 2 中提交表单时重置表单验证
【发布时间】:2016-04-09 01:57:29
【问题描述】:

我必须在验证的同时重置我的表单。有什么方法可以将表单的状态从 ng-dirty 重置为 ng-pristine。

【问题讨论】:

标签: angular angular2-forms


【解决方案1】:

似乎还没有对此的支持。 我见过的一种解决方法是在提交后重新创建表单,这显然既麻烦又丑陋。

另见

【讨论】:

【解决方案2】:

如果您使用模型驱动的表单,即 ngFormModel,提交后再次定义 controlGroup 将解决此问题。参考此link

【讨论】:

【解决方案3】:

我最近考虑过这一点,因为目前(2016 年 5 月)Angular2 中还没有为此构建任何东西。

考虑到用户无法输入'undefined'或'null',而验证主要用于向用户显示表单错误,然后只需将控件值重置为Null

myControl.updateValue(null);

当您决定在您的 UI 中显示控制错误时,您需要添加此条件,只需添加

if (myControl.value !== undefined && myControl.value !== null) {
   //then there is reason to display an error
}

(此检查是因为 Validators.Required 将空白内容视为有效)

希望这会有所帮助。

【讨论】:

    【解决方案4】:

    我在 RC.5 中这样做,我在模板中定义我的表单元素。

    <form (ngSubmit)="submit(); form.reset()" #form="ngForm">
    

    通过表单提交或用ViewChild 观看它根本不起作用,这对我来说已经足够了。

    【讨论】:

    • 我用过这个。我在angular2。是的,它重置了表格。但是会影响验证。我可以在字段中没有任何内容的情况下提交表单。即使在这种情况下 isValid 属性为 false,表单也不会显示警报消息。原因应该是表单被重置。
    • 它不会清除与#form 关联的原始、错误提示和验证器。
    【解决方案5】:

    在更新的版本中(在我的例子中是 Angular 2.4.8),这很容易:

    将控件标记为 prestine 并因此再次有效。

    private resetFormControlValidation(control: AbstractControl) {
        control.markAsPristine();
        control.markAsUntouched();
        control.updateValueAndValidity();
    }
    

    【讨论】:

      【解决方案6】:

      这是它目前在 Angular 4.1.0 - 5.1.3 上的工作方式:

      class YourComponent {
          @ViewChild("yourForm")
          yourForm: NgForm;
      
      
          onSubmit(): void {
              doYourThing();
      
              // yourForm.reset(), yourForm.resetForm() don't work, but this does:
              this.yourForm.form.markAsPristine();
              this.yourForm.form.markAsUntouched();
              this.yourForm.form.updateValueAndValidity();
          }
      }
      

      【讨论】:

      • 如果您使用 Angular 材质输入,您可以使用 yourForm.resetForm('') 使它们再次有效。但是你还需要其他代码。
      • 不幸的是,这似乎不适用于 Angular 6.1.0,输入被标记为无效。
      • 在 Angular 6 中定义变量 submit:boolean 并赋予初始值 false。然后提交表单提交值赋值为真。然后在响应提交值中分配 false 并重置表单
      • this.supplerService.AddMetrics(add).subscribe( (myMetrics)=>{ console.log(myMetrics); this.resetForm(); this.viewMetrics(); // this.metricsform. controls.metricsName.setErrors(null); }, (err)=>{ console.log(err); } );
      • resetForm(){ this.submitted = false; this.metricsform.reset(); }
      【解决方案7】:

      from.resetForm()

      我几乎尝试了所有方法,我发现唯一真正将 form.submitted 重置为 false 的是:

      在您的模板中,将您的表单发送到提交功能:

      <form name="form" class="form-horizontal" (ngSubmit)="f.form.valid && submit(f)" #f="ngForm" novalidate>
      

      在您的 component.ts 文件中,包含以下内容:

      // import NgForm
      import { NgForm } from '@angular/forms';
      
      // get the passed in variable from the html file
      submit(myForm: NgForm): void {
      
          console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);
      
          // This is the key!
          myForm.resetForm();
      
          console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);
      
      
      }
      

      console.log 值输出以下内容 - 请注意它会重置所有值。

      有效真假假真真假假

      无效假真真假假真真

      【讨论】:

      • 效果很好,但有一个问题。状态变为无效并保持不变。它不会更改为具有新值的有效。一种错误,也许我不知道。我需要刷新页面以进行新提交。
      【解决方案8】:

      这在 Angular 5 中使用模板驱动表单对我有用(它不适用于响应式表单)

      <form #myForm = "ngForm" (submit)="callMyAPI(); myForm.resetForm()">
      

      这会重置表单值和验证。

      【讨论】:

      • @Ashwin ,这将适用于模板驱动的表单 (formsModule) 而不适用于模型驱动的表单 (reactiveFormsModule)。
      【解决方案9】:

      Benny Bottema's answer 开始,我能够在 Angular 6 中使用 resetForm() 重置表单,包括验证。

      class YourComponent {
      
         @ViewChild("yourForm")
         yourForm: NgForm;
      
          onSubmit(): void {
           doYourThing();
           this.yourForm.resetForm();
          }
      }
      

      【讨论】:

        【解决方案10】:

        感谢大家在这里的回答。他们为我指明了正确的方向。

        Angular 6 和 Angular 材质

        <form #myForm="ngForm" [formGroup]="formGroup" (ngSubmit)="submit()">
        

        然后

        @ViewChild('myForm') myForm: NgForm;
        formGroup = new FormGroup({...});
        submit() {
          if (this.formGroup.pristine ||
          this.formGroup.untouched ||
          !this.formGroup.valid
        ) {
            return;
          }
        
          .... do with form data
        
          this.formGroup.reset();
          this.myForm.resetForm();
        }
        

        【讨论】:

          【解决方案11】:

          如果您使用 Angular Material 并使用 &lt;mat-error&gt;,那么它对我有用的唯一方法就是这样。 您必须使用 FormGroupDirective。

          @ViewChild(FormGroupDirective) formDirective: FormGroupDirective;
          
          submitBtnClick() {
            this.formDirective.resetForm();
          }
          

          【讨论】:

            【解决方案12】:

            Angular 8 中的这个解决方案在反应形式中对我有用

            将您的表单命名为这样

            <form #regForm="ngForm">
            

            使用 ViewChild 创建 UI 表单对象

            @ViewChild('regForm', {static: false}) myForm: NgForm;
            

            在提交调用后使用它。

            this.myForm.resetForm();
            

            提交了错误的验证

            this.submitted = false; 
            

            【讨论】:

            • 这个没必要,在formGroup对象上调用reset就够了-
            【解决方案13】:

            Angular 8 Form 重置验证错误

            创建表单:

             this.userForm = this.formBuilder.group({
              firstName: ['', [Validators.required, Validators.minLength(2)]],
              email: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')]]});
            

            重置表格:

            this.userForm.reset();
            this.userForm.controls.userEmail.setErrors(null);
            

            【讨论】:

              【解决方案14】:

              app.component.html

              #formDirective="ngForm" 并将formDirective 传递给onSubmit 方法对于重置mat-error 等错误样式至关重要。检查#4190 以关注此错误并深入解释why it's needed and how it works under the hood

              <form [formGroup]="contactForm" (ngSubmit)="onSubmit(contactForm.value, formDirective)" #formDirective="ngForm"> 
                <!-- Your input elements... -->
                <button [disabled]="!contactForm.valid">Submit</button>
              </form>
              

              app.component.ts

              记住你需要从@angular/forms(Angular/Material 9)导入的FormGroupDirective。要使表单为空调用this.contactForm.reset(); 并且表单将为invalid,这很好。但是,您还需要重置不需要的验证器样式,这是一种不同的方法,即formDirective.resetForm();

              注意formDirectiveformData 之间的区别及其不同的内置方法。

              import { FormGroupDirective } from '@angular/forms';
              
              public contactForm: FormGroup = this.formBuilder.group({
                // Your input elements...
              });
              
              public onSubmit(
                formData: FormGroup,
                formDirective: FormGroupDirective
              ): void {
                this.contactForm.reset(); // Reset form data
                formDirective.resetForm(); // Reset the ugly validators
              }
              

              【讨论】:

              • 对于像我一样苦苦挣扎的未来读者,这是 Angular 9 唯一可行的解​​决方案。
              • 这不适用于 Angular 12。
              【解决方案15】:

              在使用YourformName.reset() 进行重置时,我遇到了验证错误问题。 所以在你的 .ts 文件中使用YourformName.resetForm()。它现在工作正常。

              我在 Angular 中使用模板驱动表单。

              【讨论】:

                【解决方案16】:

                在最新的 Angular 版本中,您只需要运行 this.form.reset()它将所有内容标记为原始和未触及的所有内容),然后运行 ​​update value and validity for all the child form controls/groups/arrays

                不幸的是,对于嵌套控件,没有手动遍历子项的直接方法,至少目前是这样。

                【讨论】:

                  【解决方案17】:
                  <form #formDirective="ngForm" (ngSubmit)="submitForm(formDirective)">
                  

                  在你的组件类中,调用 formDirective.resetForm():

                  private submitForm(formDirective): void {
                      formDirective.resetForm();
                      this.myForm.reset();
                  }
                  

                  【讨论】:

                    【解决方案18】:

                    Angular 反应式表单

                    onCancel(): void {
                        this.registrationForm.reset();
                        this.registrationForm.controls['name'].setErrors(null);
                        this.registrationForm.controls['email'].setErrors(null);
                      }
                    

                    【讨论】:

                      【解决方案19】:

                      只需循环表单控件并使其保持原始状态

                           (Object as any).values(this.mainForm.form.controls).forEach((control: FormControl) => {
                              control.markAsUntouched();
                              control.markAsPristine();
                            });
                      

                      【讨论】:

                        猜你喜欢
                        • 2018-03-13
                        • 1970-01-01
                        • 2017-03-06
                        • 2016-08-07
                        • 2018-01-11
                        • 1970-01-01
                        • 2020-10-15
                        • 2016-01-03
                        • 2020-04-10
                        相关资源
                        最近更新 更多