Handling oneOf Cases in Angular Forms
Some forms require supporting one of multiple cases. For example, we can create a new task and assign it to a single user or a group of users. If users choose a single user, we want to show them a list of users; if they choose a group, we want to show them a list of groups.
To process the request, the server needs the following body signature:
In our case, we’re using ts-proto
, which generates the cases like this, but you can modify it to suit your needs. Let’s see how we can build our form so it can handle the oneOf
use cases both in template driven and reactive forms.
Using Template Driven Forms
We’ll use the ngModelGroup
directive to create the assignee group. Then, we’ll display the right select box according to the assignee
type that was selected:
Our dynamic form object is created automatically using template-driven forms.
Using Reactive Forms
Reactive forms require more boilerplate work but give you more flexibility in case you need it (dynamic validation, for example). Let’s create the form group:
We must listen to $case
value changes observable. We clear our current case
and create a new case
form control when it emits a new value.
If we want to preserve the latest value in this case, we can persist in the control
between changes:
Follow me on Medium or Twitter to read more about Angular and JS!