我对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>
<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,
],
请建议如何在提交按钮后防止页面重新加载并执行我的服务调用。