我正在使用 Angular2 模板创建表单。
当我点击按钮时,页面刷新。
我的验证工作正常。
如何在用户点击按钮时停止页面刷新?
以下是我正在使用的 HTML:-
<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/forms 导入 FormsModule,因为如果没有它,提交时的表单将不断刷新页面并在不记录的情况下静默失败控制台上的任何内容。
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{ }
关于angular - ngSubmit 以 Angular 2 形式刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39203428/