Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Submit an Angular reactive form programmatically?

How can I submit a reactive form programmatically or how to detect the button which is clicked? I have 2 buttons to submit the same form and for each button click, I want to take different actions apart from submitting.

 <form (ngSubmit)="onSubmit($event)" [formGroup]="patientInfoForm">
.
.
.

            <button id="add" type="submit" >Add Patient & Continue</button>
            <button id="addngo" type="submit" >Add Patient</button>



</form>
like image 516
Sanish Joseph Avatar asked Jun 03 '26 00:06

Sanish Joseph


2 Answers

Instead of the (ngSubmit)="onSubmit($event)" you'd have a method in your component TS file. It would look something like this:

Component TS file

addPatientAndContinue() {
    var formValue = this.patientInfoForm.value;
    // Submit the form data via a service (or HttpClient)
    // "Continue"
}

addPatient() {
    var formValue = this.patientInfoForm.value;
    // Submit the form data via a service (or HttpClient)
}

Then you would bind the click event of your buttons to the appropriate methods:

<button id="add" (click)="addPatientAndContinue()">Add Patient & Continue</button>
<button id="addngo" (click)="addPatient()">Add Patient</button>

Notice the (click) attribute on each button.

like image 103
Matt U Avatar answered Jun 05 '26 01:06

Matt U


You can use ngNoForm with your form to remove ngForm handling and to add plain javascript handler.

you can use your code as follows:

Html file.

  <form ngNoForm
    [formGroup]="patientInfoForm"
    [action]='actionLink'
    method='POST'
    #patientInfoForm>
     <input name='Email' type='hidden' [value]='currentUserEmail'>
  </form>

Ts File.

  @ViewChild('patientInfoForm') patientInfoFormElement;

  public currentUserEmail: string = '';
  public patientInfoForm = this.formBuilder.group({
    Email: ''
  });


  //Submit form programmatically
  public patientInfoFormSubmitMethod(): void {
      this.patientInfoFormElement.nativeElement.submit();
  }
like image 36
dasunse Avatar answered Jun 05 '26 02:06

dasunse