Search code examples
angularformarray

how to avoid automatic submission


In a simple angular form I am trying to emmbed a FormArray of Topics, however when I add another component tot the formArray (another topic). The form instantly submits. Can anybody see why the addTopic function also triggers the form submission?

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);
  }

  }
}

Solution

  • Assuming you are adding a topic by clicking a button, make sure the Add Topic button type is of type button. If you don't mention it, HTML will assume the type is submit (when it is associated with forms)

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