gpt4 book ai didi

Angular 形式 : How to avoid multiple NgIf divs for validation error messages?

转载 作者:太空狗 更新时间:2023-10-29 18:27:30 24 4
gpt4 key购买 nike

我想简化下面的代码:

<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 传递?

非常感谢对此的任何帮助。谢谢。

最佳答案

管理多个 Angular 表单验证消息的常用技术是将它们存储在 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 遍历所需表单控件的验证消息。

<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 Demo

关于 Angular 形式 : How to avoid multiple NgIf divs for validation error messages?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57741343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com