我希望验证器无效时弹出错误划分,但不是。
此行最有可能出错:
<div class = "danger" *ngIf="firstName?.invalid
&& (firstName?.dirty || firstName?.touched)">
预期行为:当表单无效时,输入内容应显示错误div
实际行为:没有div显示,但是对于整个表单,验证确实可以正常工作。
表单生成器:
export class DetailsComponent implements OnInit {
detailsForm;
constructor(
private formBuilder: FormBuilder,
) {
this.detailsForm = this.formBuilder.group({
firstName: ['',[Validators.required,
Validators.pattern("[a-zA-Z]+")]],
lastName: ['',[Validators.required,
Validators.pattern("[a-zA-Z\s]+")]],
email: ['',[Validators.required,
Validators.email]],
region: ['',[Validators.required,
Validators.pattern("[a-zA-Z\s]+")]],
yearOfBirth: ['',[Validators.required,
Validators.pattern("^(19[0-9]{2})|(2[01][0-9]{2})$")]],
}, { updateOn: "blur" })
}
}
模板:注意省略了其他输入以减少文本量
<div class="center-container">
<form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">
<div>
<label for="firstName">First Name</label>
<input id="firstName" type="text" formControlName="firstName">
<div class = "danger" *ngIf="firstName?.invalid && (firstName?.dirty || firstName?.touched)">
ERROR
</div>
</div>
</form>
</div>
答案 0 :(得分:1)
尝试像这样将控件从表单对象中移除:
<div class="center-container">
<form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">
<div>
<label for="firstName">First Name</label>
<input id="firstName" type="text" formControlName="firstName">
<div class = "danger" *ngIf="firstName?.invalid && (firstName?.dirty || firstName?.touched)">
ERROR
</div>
</div>
</form>
</div>
在您的component.ts
中get firstName() {
return detailsForm.get('firstName');
}
文档:https://angular.io/guide/form-validation#built-in-validators
答案 1 :(得分:0)
<form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">
<input id="firstName" type="text" formControlName="firstName">
<div
class = "danger"
*ngIf="detailsForm.get('firstName')?.invalid &&
(detailsForm.get('firstName)?.dirty ||
detailsForm.get('firstName')?.touched)"
>
ERROR
</div>
</form>
OR
<form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">
<input id="firstName" type="text" formControlName="firstName">
<div
class = "danger"
*ngIf="detailsForm.controls.firstName?.invalid &&
(detailsForm.controls.firstName?.dirty ||
detailsForm.controls.firstName?.touched)"
>
ERROR
</div>
</form>
答案 2 :(得分:0)
尝试这样:
<form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">
<div>
<label for="firstName">First Name</label>
<input id="firstName" type="text" formControlName="firstName">
<div class = "danger" *ngIf="detailsForm.get('firstName')?.invalid && (detailsForm.get('firstName')?.dirty || detailsForm.get('firstName')?.touched)">
ERROR
</div>
</div>
</form>