55

In Angular, how I add button without submit the form?

for example I want to call onCancel without submit the form, but update button should be submit the form, and still keep the ngSubmit.

<form [formGroup]="form" (ngSubmit)="submit()">
    <p>
    <select ...>...</select>
    </p>
    <p>
    <button
        type="submit"
        mat-raised-button
        color="primary">
        update
    </button>
    <button mat-raised-button (click)="onCancel($event)">
        cancel
    </button>
    </p>
</form>
Jon Sud
  • 10,211
  • 17
  • 76
  • 174

6 Answers6

137

Just add type='button' to it. A button without any defined type in a form acts like a submit button for the form.

Sachin Gupta
  • 4,981
  • 3
  • 16
  • 32
25

There are three types of buttons:

  • submit : submits the current form data. (This is default.)
  • reset : rsets data in the current form.
  • button : just a button. Its effects must be controlled by something else (that is, with JavaScript).

so you only need to update the type attribut to button

template

<button type="button" mat-raised-button (click)="onCancel($event)">
    cancel
</button>

resources

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
4

You can add $event.preventDefault() to button click event

<button mat-raised-button (click)="onCancel($event); $event.preventDefault()">
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
4

Remove (ngSubmit)="submit()" in the form tag and put it in button like so:

<button
    (click)="submit()"
    mat-raised-button
    color="primary">
    update
</button>
Murtuza
  • 308
  • 2
  • 14
4

You can use the type="button", if you don't mention any type then by default the button is considered as submit type. So you code should look something like this for the non submit button.

<button type="button" mat-raised-button (click)="onCancel($event)">
        cancel
</button>
Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
0

overall i don't like idea that default button type is submit, i created following directive to make things right, buttons witout type set explicitly defaults to button:

@Directive(
{
   selector: 'button:not([type])'
})
export class ButtonTypeDirective implements OnInit
{
   constructor(private el: ElementRef<HTMLButtonElement>, private renderer: Renderer2) 
   {
   }

   public ngOnInit()
   {
       this.renderer.setAttribute(this.el.nativeElement, 'type', 'button');
   }
}
sanjuro
  • 1,611
  • 1
  • 21
  • 29
  • I wish there was some sort of linter/formatter that would make sure the type is defined. I couldn't find such a thing and I'm considering using this approach, since it happens very often that I forget to add the button type and that results in unintentional form submissions. – Andrei Cojea Aug 24 '22 at 08:13