Pocket - How To Create A Complex Form in Angular
Pocket - How To Create A Complex Form in Angular
Angular?
By Emily Xiong • medium.com • 6 min
View Original
Before We Start
HTML Form
We don’t need to re-invite the wheels, we are still using HTML form.
Here are some things to we could use:
With reactive form, it would be easier to track the form status and
integrate with NGXS.
Dynamic Validation
For example, I got this “My shipping address is same as my billing
address” checkbox. Whether this checkbox got check would affect
the validation on the shipping address.
Checked
Unchecked
I also got a radio group for users to choose whether they want to
checkout as a guest or create a account.
Subscribe on the value changes and manually set and clear validators
FormGroupErrorStateMatcher class
So if user try to submit the invalid form, it will highlight all the fields
with errors:
Invalid form got submitted
In short,
NgxsModule.forFeature([FormsState]), NgxsFormPluginModule
Integrate with NGXS
Integrate with NGXS is pretty straightforward,
In this example, I got a few forms, so the default state for my forms
module is:
Now I got form values in the state, when I navigate back to a page,
already entered form value will persist.
Clear State
Once the form is submitted, I need to clear the entire form state. To
do so, use the library ngxs-reset-plugin , so I only need to dispatch
an action:
this.store.dispatch(new StateReset(FormsState));
Summary
Above are some challenges I ran into when I create to create a
complex form and how I solve those challenges. Of course there are
definitely other ways to work around it.
Working with forms is not an easy task, hopefully, my blog will help
you to finish this task faster.