angularangular-reactive-formscontrolvalueaccessorangular16angular-controlvalueaccessor

Angular ControlValueAccessor detect parent validator changes


When implementing a ControlValueAccessor I need to dynamically display some content based on whether or not the control is required. I know I can do this to get the control:

readonly #control = inject(NgControl, {self: true})
protected parentRequires = false

ngOnInit(): void {
  this.#control.valueAccessor = this

  this.parentRequires = this.#control.control?.hasValidator(Validators.required) ?? false
}

but that only checks to see if it's currently required. What I am not seeing though is how to detect changes. The parent is going to toggle the required attribute on/off based on other actions in the application.

I'm looking for something like the non-existent this.#control.control.validatorChanges


Solution

  • I did not try that, but the idea is that Angular will trigger full validation when input validators are modified. So you can implement Validator directly in your ControlValueAccessor (yes, it can be done) just to have sort of callback when validation fires and check this.#control.control?.hasValidator(Validators.required) there.