我正在处理必须显示验证错误的角度形式。为此,我实现了要在视图中显示的错误数组。但是我的dom结构的问题是,如果我对表单元素遇到了多个验证问题,那么所有错误都会显示出来。但是我期望的是在解决第一个错误后显示一个错误消息,而我必须显示其他错误。如何使用css或任何其他方式显示第一个错误,以角度方式实现它。元素如果没有错误将无法生成。
<div>
<error></error>
</div>
<div>
//error element will not build if it does't have error
</div>
<div>
<error></error>
</div>
您可以具有getError函数
getError(control:any):string
{
if (control.errors)
{
if (control.errors.minlength)
return "Min lengh "+control.errors.minlength.requiredLength
if (control.errors.email)
return "invalid email"
....
}
return ""
}
而且你写一些像
<mat-error>
{{getError(form.get('email')}}
</mat-error>
<< [Update从this amazing entry of Netanet Basal被盗的想法,如果您定义一个类似的对象,我们可以改善函数getError
export const defaultErrors = {
required: (error)=>"This field is required",
minlength: ({requiredLength,actualLength})=>"Expect "+requiredLength+" but got "+actualLength,
email:(error)=>"invalid email",
}
是,是一个对象,每个属性是一个函数我们的函数getError就像
getError(control) { const firstKey = Object.keys(control.errors)[0]; return defaultErrors[firstKey]?defaultErrors[firstKey](control.errors[firstKey]): "unknowed error" }