Angular Reactive forms : how to reset form state and keep values after submit

前端 未结 7 1856
逝去的感伤
逝去的感伤 2020-12-29 18:42

In an Angular reactive form. How to reset only the state of form after successful submit?

Here is the process:

  • Create the form and
7条回答
  •  孤独总比滥情好
    2020-12-29 19:13

    Some time this.myForm.reset(this.myForm.value); may not reset to initial values So it is better to create a separate function to initialize the form and call it in ngOnInit() and before call this.myForm.reset(this.myForm.value);

    ngOnInit(){
      myFormValues();
    }
    
    myFormValues() {
      this.myForm= this.fb.group({
          id: ['', Validators.required],
          name: ['', Validators.required],
        });
    }
    
    submitForm() {
      // save data
      myFormValues();
      this.myForm.reset(this.myForm.value)
    }
    

提交回复
热议问题