Angular Two buttons to submit a form but with different purpose

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

}

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


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

Try this.

In your component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  form: FormGroup;
  nextClicked = false;


  constructor(private fb: FormBuilder) {
   this.form = this.fb.group({
     age: [20],
     name: ['asdas']
   });
  }

  public onSubmit(): void {
    if(this.nextClicked) {
     ////
    }else {
      ////
    }

  }

  public onNextClick(): void {
    this.nextClicked = true;
  }

  public onPreviousClick(): void {
    this.nextClicked = false;
  }
}

And in your component.html

<div>
  <form [formGroup]="form" (ngSubmit)="onSubmit()">
    <input formControlName="age">
    <input formControlName="name">
    <button type="submit" (click)="onNextClick()">Next</button>
    <button type="submit" (click)="onPreviousClick()">Previous</button>
  </form>
</div>

And you can find a working example in this stackblitz.

You can add two separate event handlers for the click events in the two submit buttons. Those event handlers will be triggerd before the onSubmit method. You can use those two event handlers to update a state in the component to identify whether the use clicked on next or previous button.

And depending on that state you can direct the user to diferent pages on onSubmit method.