简体   繁体   English

使用 angular 中的 css 显示 dom 中的第一个元素并隐藏其他所有元素

[英]show the first element in the dom and hide other all using css in angular

I am working on the angular forms where i have to display the validation errors.我正在研究 angular forms ,我必须在其中显示验证错误。 To do this i have implemented the array of error to display in the view.为此,我实现了要在视图中显示的错误数组。 but the issue with my dom structure is if i get multiple validation issue for the form element then all errors are getting displayed.但是我的 dom 结构的问题是,如果我收到表单元素的多个验证问题,那么所有错误都会显示出来。 But what i am expecting is to display one error message after resolving the first error i have to display it other.但我期望的是在解决第一个错误后显示一个错误消息,我必须显示它。 How to show the first error using css or any other way to implement it in angular.如何使用 css 或任何其他方式在 angular 中显示第一个错误。 element will not get build if it doesn't have error.如果没有错误,元素将不会被构建。

<div>
<error></error>
</div>
<div>
//error element will not build if it does't have error
</div>
<div>
<error></error>
</div>

DOM 结构

You can has a function getError你可以有一个 function 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 ""
  }

And you write some like你写一些像

 <mat-error>
      {{getError(form.get('email')}}
 </mat-error>

Update idea stolen from this amazing entry of Netanet Basal , we can improve our function getError if you define a object like更新Netanet Basal 的这个惊人条目中窃取的想法,如果您定义 object 之类的,我们可以改进我们的 function

export const defaultErrors = {
  required: (error)=>"This field is required",
  minlength: ({requiredLength,actualLength})=>"Expect "+requiredLength+" but got "+actualLength,
    email:(error)=>"invalid email",

}

Yes, is an object, each property is a function是的,是一个 object,每个属性都是一个 function

Our function getError is like我们的 function getError 就像

  getError(control)
  {
    const firstKey = Object.keys(control.errors)[0];
    return defaultErrors[firstKey]?defaultErrors[firstKey](control.errors[firstKey]):
                                   "unknowed error"
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM