Angular - Is it possible to use a control's path instead of its name within nested reactive forms?

Viewed 736

To put it simply, when using nested reactive forms, is it possible to have something like this :

<!-- DESIRED -->
<form [formGroup]="rootFormGroup">
  <custom-input formControlName="nestedFormGroup.someVariable"></custom-input>
</form>

Instead of this :

<!-- CURRENT STATE -->
<form [formGroup]="rootFormGroup">
  <div formGroupName="nestedFormGroup">
    <custom-input formControlName="someVariable"></custom-input>
  </div>
</form>

A bit of context : our "custom inputs" require the full path to the control (as well as the rootFormGroup, although it's been left out of the snippet) in order to call some services such as :

  • cross-validation with other variables in the root form.
  • loading the label for the input
  • for <select>-derived custom inputs, loading the options

We could change the latter two to use the name instead of the full path (as long as we do not use the same name twice in different nested groups), but the cross-validation uses rootFormGroup.get(...), which in turns calls for the path.

Of course, it's possible to inject both (eg : <custom-input path="nestedFormGroup.someVariable" formControlName="someVariable">) but that's not terribly dry.

For the same reason, I'd like to avoid using the formControl directive (eg : <custom-input path="nestedFormGroup.someVariable" [formControl]="rootFormGroup.get('nestedFormGroup.someVariable')">)

If push comes to shove, I can probably manage with some vaguely recursive function to inspect any FormGroup/FormArray stemming from rootFormGroup in order to find a control with only its name (as opposed to its full path), but that is not entirely satisfying either.

Nothing critical here, but any help or comment is most definitely welcome !

0 Answers
Related