验证不会传播到Angular中的Custom Form Control ng-select [英] Validation is not propagate to Custom Form Control ng-select in Angular

查看:99
本文介绍了验证不会传播到Angular中的Custom Form Control ng-select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 9应用程序中使用了带有自定义表单控件的反应性表单.

I'm using Reactive Form with Custom Form Control in my Angular 9 application.

我用自定义表单控件包装了 ng-select 控件.

I wrapped my ng-select control with Custom Form Control.

我在验证方面遇到问题.我将formControl设置为必需. 文档说 ng-invalid css类应设置为ng-自动选择.但是实际上,使用自定义表单控件无法正常工作.没有设置css类,但是设置了包装器类.我是在做错什么还是这是图书馆的问题?

And I have problem with validation. I set formControl to be required. Documentation says that ng-invalid css class should be set to ng-select automatically. But in fact with custom form control it doesn't work properly. The css class is not set, but the wrapper class is. Am I doing something wrong or this is library issue?

检查stackblitz:

Check stackblitz: https://stackblitz.com/edit/angular-rmvttg-ex63ka?file=src/forms-single-select-example.component.html&fbclid=IwAR2robtd_15khTVhmW59lLhn21HOHl_yYTrCWKaPRmfUt1QVvUn3n8V4Vjo

推荐答案

DiPix,问题在于Angular将控件状态CSS类添加到自定义控件中,而不是添加到属于内部控件的ng-select中

DiPix, the problem is that Angular add the control status CSS classes to your custom control, NOT to the ng-select that belong to your inner control

您可以注入ngControl并检查control.control.invalid和control.control.touched

You can inject the ngControl and check about control.control.invalid and control.control.touched

constructor(private injector:Injector){}
ngOnInit()
{
   this.control = this.injector.get(NgControl);
}

然后您可以使用类似

  <ng-select #mySelect  [ngClass]="{'ng-invalid':control?.control.invalid,
                                    'ng-touched':control?.control.touched}"
   ....>

另一个方法是询问父母的班级.因此,如果您定义了类似

Another aproach is ask about the class of the parent. So if you defined a getter like

get parentClass()
{
  const match = /class=\"(.*?)\">/.exec(this.element.nativeElement.parentElement.innerHTML);
  return match[0].split('"')[1]
}

constructor(private element:ElementRef){}

您可以使用

<ng-select #mySelect  [ngClass]="parentClass" 
  ...>

您可以在您的分叉堆叠闪电战

注意:无论如何,无需包装ng-select,就无需创建自定义表单控件,只需一个带有

NOTE: Anyway, to wrapper a ng-select, is unnecesary create a custom form control, just a simple component with a @Input

@Input()control:any

您用作

    <mycontrol [control]="someForm.get('someControl')"></mycontrol>

您可以在 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆