0
votes

I am trying to submit form dynamically from ts file.

Form

<form [formGroup]="mainForm" #mainFormEle (Submit)="doNothing()">
.....
</form>

and the ts

  @ViewChild('mainFormEle',{static:false}) mainFormEle

  doNothing(){
    ..
    console.log('came in')
    ..
  }

  mainFunc(){
    ..
    this.mainFormEle.nativeElement.submit()
    ..
  }

But the above block reloads the page on submit. And never goes into doNothing(). Also tried with (ngSubmit) and (onSubmit)

2

2 Answers

0
votes

It's likely that you have a button within that form. For it not to trigger the native action of submitting the form. You have to explicitly add `type="button" on the button.

e.g.

<button type="button">
  <!-- rest of the button -->
</button>
0
votes

I found the solution.

  1. Introduced a submit button.
  2. Instead of submitting the form from ts, Just triggered the click event on the button.
<button type="submit" #submitButton></button>

or

<button type="submit" hidden #submitButton></button>
@ViewChild('submitButton',{static:false}) submitButton

  doNothing(){
    ..
    console.log('came in')
    ..
  }

  mainFunc(){
    ..
    this.submitButton.nativeElement.click()
    ..
  }

And now it works.