如何避免自动提交

how to avoid automatic submission

在一个简单的 angular 表单中,我试图嵌入主题的 FormArray,但是当我将另一个组件添加到 formArray(另一个主题)时。表单立即提交。谁能看出为什么 addTopic 函数也会触发表单提交?

export class RecommendationCreateFormComponent implements OnInit {
  recommendationForm: FormGroup;
  formSubmitted = false;


  constructor(private fb: FormBuilder, public getRecommendationservice: GetRecommendationService) { }

  ngOnInit () {

    this.recommendationForm = this.fb.group ({
      guideline: [''],
      recommendationContent: [''],
      levelOfEvidence: [''],
      rclass: [''],
      topics: this.fb.array([]),
    });
    this.addTopic();
  }
  get topics() {
    return this.recommendationForm.get('topics') as FormArray;
  }

  addTopic () {
    const newTopic = this.fb.group({
      topicData: '',
    });
    this.topics.push(newTopic);
  }

  deleteTopic(i) {
    this.topics.removeAt(i);
  }

  submitNew(form: NgForm) {
    console.log ('here we go');
    const formModel = this.recommendationForm.value;
    const topicDeepCopy: Topic [] = formModel.topics.map((topic: Topic) => Object.assign({}, topic)
      );
    const saveRecommendation: Recommendation = {
      id: null,
      recommendationContent: formModel.recommendationContent as string,
      guideline: formModel.guideline as string,
      levelOfEvidence: formModel.levelOfEvidence as string,
      rclass: formModel.rclass as string,
      topics: topicDeepCopy,
    };
    this.getRecommendationservice.addRecommendation(saveRecommendation);
  }

  }
}

假设您通过单击按钮添加主题,请确保“添加主题”按钮类型为 button 类型。如果您不提及它,HTML 将假定类型为 submit(当它与表单关联时)

<button type="button">Add Topic</button>

如果您使用按钮添加主题,请确保该按钮的类型为 button

表单 中不带 type 属性的任何按钮都被视为提交按钮,单击它会提交您的表单。

<button type="button" (click)="addTopic()"> Add topics </button>