如何避免自动提交

时间:2018-12-23 10:20:14

标签: angular formarray

我试图以简单的角度形式嵌入主题的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);
  }

  }
}

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

表单中没有type属性的任何按钮都被视为“提交”按钮,单击该按钮将提交您的表单。

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