如何在Angular 7中防止表单提交时页面重新加载

16

我对Angular不熟悉。我面临着一个提交按钮的问题。当我点击类型为submit的按钮时,它会重新加载整个页面,而不是调用我的服务API。

我在表单标签中添加了(keydown.enter)="$event.preventDefault()",同时在按钮点击方法中也尝试了event.preventDefault()。但都没有起作用。

请检查下面的代码:

<form  #createForm="ngForm" class="login-form text-center" (ngSubmit)="Update()" (keydown.enter)="$event.preventDefault()">
       <table cellpadding="5" class="mx-auto">
          <tr>
            <td>
              <label class="white pr-2" for="email" autofocus>Email</label>
            </td>
            <td>
              <input name="email" id="email" type="text" [(ngModel)]="email" required  #name="ngModel"class="d-inline-block w-100" >
            </td>
          </tr>

          <tr>
            <td></td>
            <td class="text-left">

                <button class="d-inline-block text-left lh-100" id="login" type="submit"  [disabled]="!createForm.form.valid">Change Password
                 </button>&nbsp;
                 <button class="float-right lh-100" style="background-color:grey" [routerLink]="'/login'" >Back to Login</button>

             </td>
          </tr>
        </table>
      </form>

这是我的.ts代码。按钮更新方法。

Update()
  {

   this.userservice.changePassword(this.email).pipe(first())
    .subscribe(
        data => 
        {
            if(!data.message)
            {
              this.errorMsg = data.message;
            }
           else 
            {
              this.errorMsg = data.message;
            }
        },
        error => {
          this.errorMsg = error.Message;
        });

  }

这里是服务代码

 changePassword(EmailId: string) {

        return  this.http.get<Validations>(`${environment.apiUrl}/User/SendMail?userName=` + EmailId+`&subject=`+''+`&message=`+''+`&mailType=`+'changepassword');
    }

应用程序模块文件

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GridModule } from '@progress/kendo-angular-grid';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { LoginComponent } from './common/login/login.component';
import { ForgotPwdComponent } from './common/forgotPwd/forgotPwd.component';
import { BlankComponent } from './common/blank/blank.component';
import { ResetComponent } from './common/reset/reset.component';





@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    ForgotPwdComponent,
    ResetComponent,
    BlankComponent,


  ],
  imports: [
    BrowserModule,

    FormsModule,
    AppRoutingModule,
    GridModule,
    BrowserAnimationsModule,
    HttpClientModule,


  ],
请建议如何在提交按钮后防止页面重新加载并执行我的服务调用。
7个回答

27
如果 onSubmit 发生错误,则会刷新页面。 因此,请确保您已从 @angular/forms 中导入FormsModuleReactiveFormsModule 到您的各自的 module.tsapp.module.ts中。

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent }  from './app.component';
import { HeroFormComponent } from './hero-form/hero-form.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    AppComponent,
    HeroFormComponent
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

我已经在app.module.ts中导入了import { FormsModule } from '@angular/forms';。 - Karthik
你能分享你的 app.module.ts 文件吗? - Sarjerao Ghadage
同时检查是否已导入ReactiveFormsModule,如果没有则导入它。 - Sarjerao Ghadage
你错过了ReactiveFormsModule,请添加它。 - Sarjerao Ghadage
1
好的,非常感谢您的支持。 - Karthik
显示剩余2条评论

6
如果您按照以下方式将FormsModule添加到app.module.ts中:
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
  ],
  ...
})

并使用 ng serve 重新启动它(如果 ng serve 进程正在运行,则停止它并再次运行),那么这个问题就会被解决。


4

问题的根本原因在于表单中存在错误

原因可能有很多,下面是我遇到的一个场景,希望对他人有所帮助。

在我的 Angular 12 应用程序中

我使用了类似于:

<div [formGroup]="testForm" (ngSubmit)="save()">

相反应该是这样的

<form [formGroup]="testForm" (ngSubmit)="save()">

1

将按钮的type属性从submit更改为button或其他任何类型。


1
使用 (submit) 防止重新加载页面,返回 false。

0
在 Angular 12 中,监听提交事件的是 `[FormGroup]` :

`FormGroup` 指令监听表单元素发出的提交事件,并发出一个 ngSubmit 事件,您可以将其绑定到回调函数上。查看文档

所以您需要具备以下条件:
  • 在您的 `<form>` 元素上有一个 `[FormGroup]`
  • `(ngSubmit)` 和组件方法
  • 已加载 `ReactiveFormsModule`
  • 在您的组件类上有一个公共的 `FormGroup` 属性,最好与表单输入中的一些属性匹配

0
确保直接从开放的表单标签中使用 (ngSubmit)="signIn()",而不是通过按钮或 href 标签提交...以下是我的例子,这可能对某人有所帮助。
如果你使用按钮,失败的提交后会重新加载页面。
                <form
                [formGroup]="signInForm"
                #signInNgForm="ngForm"
                (ngSubmit)="Update()">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接