验证不会传播到 Angular 中的自定义表单控件 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
cssclass 应自动设置为 ng-select.但实际上自定义表单控件无法正常工作.未设置 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?
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,不需要创建自定义表单控件,只需一个带有 @Input
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>
您可以在 这是另一个堆栈闪电战