Sharing complex form logic in Angular

Posted on Jun 15, 2021

There’s an Angular application which works with the same form structure on different layouts. Let’s think about a possible wizard, build on a stepper which asks all information while walking the user from step to step. But there’s also another scenario, where the user will work with the entire form in a single page. In enterprise application where forms are composed from several inputs these are common use-cases.

Well, dealing with that kind of scenario is not so easy. You could create a form for each case or maybe decide to go with a single form, shared across all application. In any case, you could deal with some complex validation that needs to be configured in each and every use-case. Consider setting some dynamic logic: validators which are involved only in specific conditions, fields that enabled/disabled dinamically and some autocomplete logic.

For that use case I thought that sharing the forms (there could be more than one in that scenario!) in a dedicated service. In this way you’ll set all stuff in a single place, which will have that particular responsability. To prove this idea I created a PoC, which can be found here.

What you see on the PoC is a very simple concept, just to prove the idea. Again, consider a form with an high level of complexity and a lot of business logic working under the hood: with this pattern you can share this stuff across all application.