Angular 2: Form submission canceled because the form is not connected

前端 未结 10 731
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 13:03

I have a modal that contains a form, when the modal is destroyed I get the following error in the console:

Form submission canceled because the form i

10条回答
  •  春和景丽
    2020-12-08 13:05

    In case that submitting the Form is being accompanied by the component's destroying, the Form submitting fails in race condition with the detaching of the Form from the DOM. Say, we have

    submitForm() {
      if (this.myForm.invalid) {
        return;
      }
      this.saveData(); // processing Form data
      this.abandonForm(); // change route, close modal, partial template ngIf-destroying etc
    }
    

    If saveData is async (for example it saves the data via API call) then we may wait for the result:

    submitForm() {
      this.saveDataAsync().subscribe(
        () => this.abandonForm(),
        (err) => this.processError(err) // may include abandonForm() call
      );
    }
    

    If you need to abandon the Form immediately, a zero-delay approach also should work. This guarantees the DOM detachment to be in the next event loop after the Form submission has been called:

    submitForm() {
      this.saveData();
      setTimeout(() => this.abandonForm());
    }
    

    This should work regardless of the button type.

提交回复
热议问题