ngSubmit refreshes the page in Angular 2 form

AngularTypescript

Angular Problem Overview


I am using Angular2 template for creating a form.

When i click on button, the pages refreshes.

My validations are working fine.

How can i stop page refresh when user clicks on button?

Following is HTML I am using:-

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">Add Employee</h3>
        {{model | json}}
        {{EName.errors | json}}
    </div>
    <div class="panel-body">  
        <form (ngSubmit)="onSubmit(empForm)" #empForm="ngForm" autocomplete="off" novalidate>
        
        <div class="form-group">
            <label for="EmployeeName">Employee Name</label>
            <input type="text" class="form-control" id="EmployeeName" placeholder="Employee Name" required [(ngModel)]="model.EName" name="EName" #EName="ngModel" ngControl="Ename" #EName="EName" >
            <div *ngIf="EName.touched && EName.errors" >
                <div *ngIf="EName.errors.required"  class="alert alert-danger">
                    Employee Name is required
                </div>
            </div>
        </div>
        <div class="form-group">
            <label for="Age">Age</label>
            <input type="text" class="form-control" id="Age" name="Age" placeholder="Age" [(ngModel)]="model.Age" ngControl="Age">
        </div>
        <div class="form-group">            
            <label for="Sex">Sex</label>
            <div class="d-block">
                <label class="radio-inline">
                    <input type="radio" name="sex" id="Male" value="0" (click)="model.Sex=$event.target.value"> Male
                </label>
                <label class="radio-inline">
                    <input type="radio" name="sex" id="Female" value="1" (click)="model.Sex=$event.target.value"> Female
                </label>
            </div>
        </div>

        <div class="form-group">
            <label for="DOJ">Date of Joining</label>
            <datepicker [(ngModel)]="model.DOJ" name="DOJ"></datepicker>
        </div>

        <div class="form-group">
            <label for="Salary">Salary</label>
            <input type="text" class="form-control" id="Salary" placeholder="Salary" [(ngModel)]="model.Salary" name="Salary">
        </div>

        <div class="form-group">
            <label for="Designation">Designation</label>
            <select id="Designation" name="designation" class="form-control" required [(ngModel)]="model.Designation" name="designation" #desig="ngForm" ngControl="Designation">
                <option value="" selected>-- Select  --</option>
                <option *ngFor="let designation of designations" value="{{ designation.id }}"> 
                    {{designation.name}} 
                </option>
            </select>
            <div [hidden]="desig.valid || desig.pristine" class="alert alert-danger">
                Please select a proper designation.
            </div>
        </div>
        <button type="submit" class="btn btn-default" [disabled] ="!empForm.form.valid">Submit</button>
        </form>
    </div>
</div>

Angular Solutions


Solution 1 - Angular

Make sure you import FormsModule from @angular/forms in the module containing your component because without it your form on submit will keep refreshing the page and failing silently without logging anything to the console.

import { NgModule }           from '@angular/core';
import { CommonModule }       from '@angular/common';

/*make sure you import it here*/
import { FormsModule }        from '@angular/forms';

 @NgModule({
  /*and add it to the imports array here*/
  imports:      [ FormsModule,  CommonModule],
  declarations: [ YourFormComponent ],
  exports:      [],
  providers:    [],
})

export class FeatureModule{ }

Solution 2 - Angular

it refreshes because there is an error in onSubmit handler.. use event.PreventDefault(); in the onSubmit :

 <form (ngSubmit)="onSubmit(empForm, $event)" ... >


public onSubmit(empForm: any, event: Event) {
  event.preventDefault();
  .... rest of your code
}

also you can just check the console output to debug the error ... make sure to mark the preserve log option

preserve log checked in devtools

Solution 3 - Angular

Use instead:

<button type="button"

The reload is caused by the default submit behavior of the browser.

Solution 4 - Angular

Update 2019/2018 - If this is happening to you on any recent version of Angular (I'm currently on 7), it's not due to a <button type="submit"...>, in-fact, that's perfectly fine, you can keep that. You can also keep the (submit) event on your <form> element.
You likely have an error somewhere else which is causing Angular to not act as intended.

  • Please make sure you have included the FormsModule or ReactiveFormsModule if you're using reactive forms.
  • Please make sure you don't have errors in your console (click f12 then navigate to Console)

Angular will not refresh the page if you have properly instantiated your Form.

Solution 5 - Angular

This worked and stopped the whole page from reloading:

  1. I changed the button type from "submit" to "button"

  2. I introduced a (click)= submitValues() inside the button props like this :

This stopped the page from reloading, I hope this helps.

Solution 6 - Angular

Refreshes the page in Angular 2 form:

Change button type from "submit" to button, no change can reflect.

Solution:

form module has to imported in your corresponding module. Because <form> without form module, consider as html form.So that form gets refresh.

<form (submit)="onSubmit()">
   <input type="text" name="firstName"/>
   <button type="submit">submit</button>
</form>

Button type with submit only able to trigger the form onsubmit()

Solution 7 - Angular

I was facing this same issue, onsubmit of my reactive form the page was getting reloaded.
I found that I had assigned value to my reactive form control using '='.
I changed the assignment using setValue() and it resolved my issue:

this.formName.controls.fieldName.setValue(value);

Solution 8 - Angular

You should be import FormsModule on the "app.module.ts". like this:

import { FormsModule } from '@angular/forms';

@NgModule({
  imports:[ FormsModule ]

About the action (click) on the

Solution 9 - Angular

User from onSubmit handler in the onSubmit :

<form id="..." (ngSubmit)="onSubmit($event)" ... >

public onSubmit(event: Event) {
  .... rest of your code
}

Solution 10 - Angular

i solve this problem by using

<button type="button">Submit</button>

instead of

<button type="submit">Submit</button>

submit keyword is responsible for page refreshing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKunalView Question on Stackoverflow
Solution 1 - AngularHamed BaatourView Answer on Stackoverflow
Solution 2 - Angularreda igbariaView Answer on Stackoverflow
Solution 3 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 4 - AngularAugie GardnerView Answer on Stackoverflow
Solution 5 - AngularAWESOME WORLDView Answer on Stackoverflow
Solution 6 - AngularVimalrajView Answer on Stackoverflow
Solution 7 - AngularNish007View Answer on Stackoverflow
Solution 8 - AngularHelder Silva CruzView Answer on Stackoverflow
Solution 9 - AngularHeverton Silva CruzView Answer on Stackoverflow
Solution 10 - Angularchander lal piterView Answer on Stackoverflow