angular reactive forms validation with behavior subject

38 views Asked by At

Hei Community, I wonder what is the best way to validate Angular Reactive Forms when there are some really dynamic fields that depend on each other and need to call API to validate.

I Have a Input, A Dropdown, A Input And another Dropdown. They depend on each other treeshaped, means the first input specifies what can be in first dropown that specieifes whats in the next input and that specifies whats in the last dropdown.

My first approach was async validation of the FormGrouo the connected FormControls belong to. But i did not get this to work.

Now My approach is to use synchonous validation and a BehaviorSubject the possible values for the controls are in. Every time a Control Changes I make an API call and fetch the Data that could satify the current values of the formcontrol. This API response is nextet to the beahviourSubject. The Behaviour subject has a subsriber, that validates the form evertime something is nextet to it (and therefore runs the validators that take the value of the behaviorsubject to validate the form).

The Value of the Behavior subject is also used for the possible values of the dropdown.

Is this the recommended solution or what is the correct form to have a solution for such a complicated validation.

I'm not a senior in angular but it seams like this is over my knowledge.

Apprechiate any respone.

Regards.

1

There are 1 answers

0
manuel On BEST ANSWER

I just wanted to share the approach I mentioned above. Asynchronous fetching of Data from Database. Synchronous Validation of the form elements.

Can you please give me feedback on this approach.

https://stackblitz.com/edit/stackblitz-starters-4db78y?file=src%2Fexample-form%2Fexample-form.component.ts

Regards Manuel