angularangular-reactive-formssubmit-button

Angular Two buttons to submit a form but with different purpose


I have an angular reactive form

<form [formGroup]="form" (ngSubmit)="onSubmit()">

I have two buttons to submit. I need to perform a common operation when users press the button, that is submit the form, but also I need to differentiate between the buttons, because I need to redirect the user to different pages, depending on the button pressed. Here is my two buttons:

<button name="Previous" type="submit" [disabled]="form.invalid"> Previous</button>
<button name="Next" type="submit" [disabled]="form.invalid">Next</button>

How can I know in the OnSubmit event which button was pressed?


Solution

  • I found an answer. A bit tricky: In the onSubmit event I check:

    var buttonName = document.activeElement.getAttribute("Name");
    

    Since one of the button must be the active element on the form when the user click it, this does the trick for me