我创建了角形的反应形式。我能够通过触摸获得控件的验证,但是通过单击“提交”按钮无法获得提交表单的验证。我的代码如下:
<form [formGroup]="myform" (ngSubmit)="SubmitDetails()">
<div class="row">
<label for="name">Name:</label>
<input type="text" id="Name" name="Name" formControlName="Name"/>
<span *ngIf="myform.controls.Name.invalid && myform.controls.Name.touched">Please Enter Name.</span>
</div>
<br/>
<div class="row">
<label for="age">Age:</label>
<input type="text" id="Age" name="Age" formControlName="Age"/>
<span *ngIf=" myform.controls.Age.invalid && myform.controls.Age.touched">Please Enter Age.</span>
</div><br/>
<button type="submit">Submit</button>
</form>
答案 0 :(得分:0)
您可以检查表单是否具有有效的formGroup属性:
this.yourFormGroup.valid;
在您的提交功能上,只需检查表单是否有效,如果是,然后继续,否则将表单标记为脏或被触摸:
submitFunction() {
if(this.yourFormGroup.valid) {
console.log('it s ok!');
}else {
this.yourFormGroup.markAsDirty();
}
编辑:我对在formGroup上使用markAsDirty有疑问,如果它不起作用,只需简单地循环来自formGroup的所有formControl,并将它们标记为dirty():
this.yourFormGroup.get('yourFormControl').markAsDirty();
答案 1 :(得分:0)
如果表单无效,则可以向按钮添加禁用状态。不确定是否可以使用您的UI / UX方法,但值得一提。
<button type="submit" [disabled]="form.invalid">Submit</button>