html - 我需要对有角度的表单进行验证
问题描述
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
ngOnInit() {
this.createFormControls();
this.createForm();
}
createFormControls(){
this.firstName = new FormControl('',Validators.required);
this.lastName= new FormControl('',Validators.required);
this.Address= new FormControl('',Validators.required);
this.age = new FormControl('',Validators.required);
this.phnumer= new FormControl('',Validators.required);
}
createForm(){
this.form = new FormGroup({
name: new FormGroup({
firstName:this.firstName,
lastName: this.lastName,
Address:this.Address,
age:this.age,
phnumer:this.phnumer
}),
});
}
我需要在 angular6 中验证一个表单,我有 5 个字段,但是需要在没有提交按钮的情况下进行验证,我必须在同一个内联中验证它们。这是我在 ts 文件中的代码现在我已经在 html 页面中实现了验证,但是验证应该在同一行中显示错误消息,而不是单击提交按钮
解决方案
您可以使用 Angular 中的内置验证器来实现这一点(https://angular.io/guide/form-validation#built-in-validators)
get
在您的组件中,创建一个表单组和一个 getter 方法,以通过父组中的方法访问表单控件。我将为单个字段提供一个示例。
createForm(){
this.form = new FormGroup({
firstName: new FormControl('', Validators.required)
});
}
get firstName() {
return this.form.get('firstName');
}
在您的 HTML 中,您可以使用条件表达式和验证属性来显示错误。
<form [formGroup]="form">
<label for="firstName">First Name
<input id="firstName" formControlName="firstName">
<div *ngIf="firstName.invalid && (firstName.dirty || firstName.touched)">
<div *ngIf="firstName.errors.required">
First Name is required.
</div>
</div>
</label>
</form>
推荐阅读
- python - 如何在我的石头剪刀布游戏中添加另一轮
- python - Python如何仅当值后选择的分隔符是数字时才拆分字符串?
- r - 根据数据框列创建多个序列
- rust - 将临时/局部变量传递给 Err
- kubernetes - kubernetes - 在同一节点上具有相同应用程序的多个 pod
- c# - 对基于 LINQ 的列表使用匿名类型而不是 var
- selenium-webdriver - 如果存在多个依赖项,Gradle 如何决定从哪个依赖项中获取类
- stripe-payments - 如何使用 Stripe 收集账单信息
- android - 为什么 Invalidate Cache/Restart 选项会导致 android studio 永久构建?
- javascript - 如何自定义图表js条形图形状?