I'm questioning the validity of my solution. My application utilizes Reactive Form, and for my CustomFormControl (which implements ControlValueAccessor), I've included a validator
myControl: ["", Validators.required]
. This validator is only required on certain pages, so it's added by the formBuilder.
However, there is also a need for validators that are always applied to that control. To achieve this, I had to introduce the token NG_VALIDATORS
, which allows me to utilize the validate()
method that gets triggered every time the control needs validation:
@Component({
selector: "my-control",
templateUrl: "./my-control.component.html",
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: MyControlComponent,
multi: true
},
{
provide: NG_VALIDATORS,
useExisting: MyControlComponent,
multi: true
}
]
})
export class MyControlComponent implements OnInit, ControlValueAccessor {
...
validate(value: AbstractControl): void {
value.setValidators(Validators.compose([value.validator, Validators.min(0), Validators.max(200)]));
}
}
It's worth mentioning that I used value.validator
in order to merge the existing validators added in the form builder with the new min
and max
validators. The functionality works as expected, but I'm unsure if this is the correct approach, since I couldn't find a similar case when searching online.