-1

I have a custom control that implements ControlValueAccessor and is only used with a reactive form. How do I tell, inside the custom control, when the required validator has been assigned or removed?

I don't want to just create an @Input for a required property as it's only used with reactive forms.

Gargoyle
  • 9,590
  • 16
  • 80
  • 145

1 Answers1

0

You needn't make nothing. A custom control validator is a "view", is the formControl who has the validators or not. See an e.g. in this stackblitz

Well, if you want to know if the control is valid or not inside the custom formControl (this allow us, e.g. show an error inside the custom form control), you need inject the NgControl

Some authors inject removing the providers and inject in constructor the ngControl

  constructor(
    @Self() public ngControl: NgControl,
  ) {
    this.ngControl.valueAccessor = this;
  }

But I prefer make in ngOnInit -with the first aproach I don't know how create a validator inside the custom form control-

  ngOnInit(){
    this.ngControl = this.injector.get(NgControl);
  }

So, we can use ngControl.valid, ngControl.errors, ngControl.touched... if you want to know if has a validator you can ask about ngControl.validator (if it's null has no validator), but I don't know if is the validator required or not

NOTE: In the example if you use the toogle button, the inner validator is clear too

Eliseo
  • 50,109
  • 4
  • 29
  • 67