角形式:如何避免验证错误消息出现多个NgIf div? [英] Angular Forms: How to avoid multiple NgIf divs for validation error messages?
本文介绍了角形式:如何避免验证错误消息出现多个NgIf div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想简化以下代码:
<div *ngIf="form1.errors?.checkDate && (form1.touched || form1.dirty)" class="cross-validation-error-message alert alert-danger">
Date can't be in the future.
</div>
<div *ngIf="form1.errors?.notAfterDate && (form1.touched || form1.dirty)" class="cross-validation-error-message alert alert-danger">
Birth Date must be after 1/1/1800.
</div>
它应该只有1个 div * ngif
并将错误消息作为值传递,而不是硬编码或使用 ngFor
?
It should have only 1 div *ngif
and pass the error message as a value instead of hardcoding or use a ngFor
?
对此,我们将提供任何帮助.谢谢.
Any help on this is much appreciated. Thanks.
推荐答案
管理多个Angular Form验证消息的常用技术是将它们存储在地图中.
A common technique to manage multiple Angular Form validation messages is to store them in a map.
public validationMessages = {
'firstName': [
{ type: 'required', message: 'First Name is required' },
{ type: 'maxlength', message: 'First Name may only contain 5 characters.' }
],
'lastName': [
{ type: 'required', message: 'Last Name is required' },
{ type: 'pattern', message: 'Last Name may not be "Smith".' }
],
'email': [
{ type: 'required', message: 'Email is required' },
{ type: 'email', message: 'Enter a valid email' }
]
}
HTML模板
在模板中,使用 NgFor
遍历验证消息以获取所需的表单控件.
HTML Template
In the template, use NgFor
to iterate through the validation messages for the desired form control.
<label>
Email:
<input type="email" autocomplete="email" formControlName="email" required>
</label>
<!-- Validation Errors -->
<div *ngFor="let validation of validationMessages.email">
<div *ngIf="profileForm.get('email').hasError(validation.type) && (profileForm.get('email').dirty || profileForm.get('email').touched)">
<small style="color:red;">{{validation.message}}</small>
</div>
</div>
示例
请参见 Stackblitz演示
这篇关于角形式:如何避免验证错误消息出现多个NgIf div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文