Search code examples
angulartypescriptcoding-styleangular-reactive-forms

Angular reactive forms - good practice


I was wondering what is the better practice to use.

So the situation looks like this: I have a form and depending on user selection I will need different (some of them may be the same) form fields.

Here is a question, should I at start of a base component (where the form is first created) add all possible fields, and use them if they are needed or should I add fields based on the option chosen by a user? (Btw added fields would be added in new components in ngOnInit())


Solution

  • Simple approaches have less side effects. The simplest approach here is to declare your entire form with all possible attributes as a property using a FormGroup or FormBuilder. When you post back to the server on submit, you can post the entire form since the attributes your users never saw would simply be null or undefined.

    You'll still have to dynamically show/hide inputs in the template, but the component code will be simpler.