我有一个小问题,例如,如果我尝试提交一个空表单,它会向我的服务器发送一个帖子请求,但我不知道如何防止这种情况
这是我的表格
b[i] = a[i + 1]
并在我的app.component.ts
中在我的构造函数中我有
<form class="form-horizontal" [formGroup]="form" #myForm="ngForm"
(ngSubmit)="save()">
<div class="form-group">
<label for="firstName" class="control-label
required">First name</label>
<input type="text" id="firstName" class="form-control"
formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label
required">Last name</label>
<input type="text" id="lastName" class="form-control"
formControlName="lastName">
</div>
和save()函数用于提交表单
this.form = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
lastName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
});
我已经尝试过如果我的保存功能中的条件if(formModel.valid)但是没有用,帮助:S
答案 0 :(得分:0)
这就是我处理表格的方式......
form: FormGroup;
constructor(
fb: FormBuilder
){
this.form = fb.group({
name: ["", Validators.required]
});
}
submit({value, valid}:{value: IForm, valid: boolean){
if(valid){
...
}
}
<form [formGroup]="form" (ngSubmit)="submit(form)">
<input formControlName="name" />
<button type="submit">submit</button>
</form>