angular - Angular 表单验证未显示在 Angular 表单错误中
问题描述
这是我的 HTML
<form [formGroup]="applicationDetailsForm" (ngSubmit)="appDetails(applicationDetailsForm.value)">
<label>Organization Name</label>
<input type="text" formControlName="appName" id="appName" required>
<p class="error_message" *ngIf="
applicationDetailsForm.get('appName').hasError('required')
&& applicationDetailsForm.get('appName').touched
&& applicationDetailsForm.get('appName').minLength
&& applicationDetailsForm.get('appName').maxLength">Provide a valid name</p>
这是我的组件
ngOnInit() {
this.applicationDetailsForm = this.formBuilder.group({
appName: new FormControl ('', Validators.compose([Validators.required, Validators.maxLength(32),
Validators.minLength(4)]))
})
表格中的错误没有显示出来。请帮忙!
解决方案
您正在测试minLength && maxLength
您的状况以显示错误消息。他们永远不会同时处于活动状态。
您也没有正确查找minLength
&maxLength
错误。它们不是FormControl
自身的直接属性——它们是errors
子属性。
你可能会有更好的运气:
*ngIf="
applicationDetailsForm.get('appName').touched && (
applicationDetailsForm.get('appName').hasError('required')
|| applicationDetailsForm.get('appName').hasError('minLength')
|| applicationDetailsForm.get('appName').hasError('maxLength')
)
"
还可以考虑采用通过 getter访问Angular 的最佳实践:FormControl
component.ts
:get appName() { return this.applicationDetailsForm.get('appName'); }
component.html
:<form [formGroup]="applicationDetailsForm" (ngSubmit)="appDetails(applicationDetailsForm.value)"> <label>Organization Name</label> <input type="text" formControlName="appName" id="appName" required> <p class="error_message" *ngIf="appName.touched && ( appName.errors.required || appName.errors.minLength || appName.errors.maxLength )">Provide a valid name</p>
推荐阅读
- php - Symfony Webpack Encore ReferenceError: function is not defined
- compilation - STM32 HAL 是否应作为预编译库包含在内
- php - after form submission display the submitted data to user in laravel
- android - 未从 Web 服务器获取数据
- mysql - MySQL:是否可以在 SELECT 语句中插入包含 OR Like?
- wso2 - wso2流处理器:流架构
- python-3.x - 我无法在 git bash 中打开 python 文件
- python - 循环遍历一个反向(列表)会增加我函数的时间复杂度吗?
- javascript - 是否有任何特定的标准或名称来记录库的端点?
- tsql - SQL:获取第一行列值不为空,否则使用第二行列