[英]Show form validation errors on submit in angular template driven form
我已经在Angular中创建了模板驱动的表单。
<form novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">
<input type="text" class="form-control" name="fullName" #fullName="ngModel" required>
<div *ngIf="fullName.errors?.required && fullName.touched" class="validation-message">Required</div>
<button type="submit">Post</button>
无效并被触摸时显示错误。 提交表单时,即单击提交按钮时,我需要显示错误。
onSubmit({value, valid}): void {
if (valid) {
console.log(value);
} else {
console.log('invalid form');
}
}
将标志设置为true时有效,并使用$ ngIf:HTML
<form #myForm="ngForm" (submit)="onSubmit(myForm)">
<input type="text" class="form-control" required [(ngModel)]="fullname" name="fullname" #input="ngModel">
<div style="color:red" *ngIf="submittedError">
Error
</div>
<br><br>
<button type="submit">Post</button>
</form>
打字稿:
submittedError;
...
onSubmit({value, valid}): void {
if (valid) {
this.submittedError=false;
console.log(value);
} else {
this.submittedError=true;
console.log('invalid form');
}
}
}
您必须使用一个额外的标志来做到这一点。
像下面一样
submitted = false;
onSubmit() { this.submitted = true; }
并将插入submitted
到*ngIf
语句中。
参考: https : //angular.io/guide/forms#toggle-two-form-regions-extra-credit
添加到答案中:ngForm暴露了一个已提交标志。 因此,只需创建一个模板变量,并对错误执行ngIf(即ngForm.submitted === true)
在onSubmit方法中,迭代所有表单控件,并简单地将它们标记为已触摸
Object.keys(form.controls).forEach(key => {
form.controls[key].markAsTouched();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.