问题
I'm using Reactive Form with Custom Form Control in my Angular 9 application.
I wrapped my ng-select control with Custom Form Control.
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
回答1:
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
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);
}
then you can use some like
<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){}
You can use
<ng-select #mySelect [ngClass]="parentClass"
...>
You can see in your forked stackblitz
NOTE: Anyway, to wrapper a ng-select, is unnecesary create a custom form control, just a simple component with a @Input
@Input()control:any
And you use as
<mycontrol [control]="someForm.get('someControl')"></mycontrol>
You can see how simple becomes in this another stackblitz
回答2:
You can fix this by passing the FormGroup
down into your subcomponent via Input
and set it to the ng-select
:
<mycontrol formControlName="someControl" [parentFormGroup]="someForm" ></mycontrol>
Component:
export class MyControlComponent implements ControlValueAccessor {
@Input() parentFormGroup: FormGroup;
...
Template:
<ng-select #mySelect
[formGroup]="parentFormGroup"
...
来源:https://stackoverflow.com/questions/60459025/validation-is-not-propagate-to-custom-form-control-ng-select-in-angular