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?
yes, multiple submit buttons can include in the html form. One simple example is given below.
Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.
If you don't have any submit button it is acceptable after all it is an element of form tag and if it is not required you may not add it with in form . This will not broke any web standard.
What are form controls in Angular? In Angular, form controls are classes that can hold both the data values and the validation information of any form element. Every form input you have in a reactive form should be bound by a form control. These are the basic units that make up reactive forms.
You can try with this solution
component.html
<form [formGroup]="form" (ngSubmit)="onSubmit(buttonType)">
<button type="submit" (click)="onSubmit('Next')">Next</button>
<button type="button" (click)="onSubmit('Previous')">Previous</button>
</form>
component.ts
onSubmit(buttonType): void {
if(buttonType==="Next") {
console.log(buttonType)
}
if(buttonType==="Previous"){
console.log(buttonType)
}
}
user1238784, you shouldn't use document directly in Angular, use ElementRef or Renderer2 instead. While this works, it's against best practices and it will break SSR if you decide to use Angular Universal at some point.
Direct DOM manipulation in Angular is big no no, you should always manipulate DOM using API provided by framework.
But you don't even need any of that, you can pass event as param like this:
<form [formGroup]="form" (ngSubmit)="onSubmit($event.submitter.id)">
and then in component you can use event to identify button that was clicked
this is how you can access the id of the input/button being used to submit the form
submitForm(event : MouseEvent) :void
{
console.log(event)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With