angular - Angular Forms:如何避免多个 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>
它应该只有 1div *ngif
并将错误消息作为值传递,而不是硬编码或使用ngFor
?
非常感谢您对此的任何帮助。谢谢。
解决方案
管理多个 Angular 表单验证消息的常用技术是将它们存储在地图中。
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
遍历所需表单控件的验证消息。
<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>
例子
推荐阅读
- python - 如何让 Django 显示整数而不是浮点数
- c++ - 我可以为 unordered_map 分配一个特定的 Mod 值吗
- sql - 比较同一列中的类别计数
- python - Anaconda 导航器启动错误
- r - 如何将 ShinyApp html 以 PDF 或其他格式输出
- javascript - 警告:缺少下一个人数
- angular - Angular EventEmitter 似乎不起作用
- typescript - typescript 获取数组值的类型,例如键的情况?
- python-3.x - 翻转嵌套列表中的位
- python - 无法使用聚合在 mongodb 中组合来自多个集合的数据?(皮蒙戈)