In the previous 5 posts of the “Angular form builder” series I demonstrated how you can generate Angular forms:
- with all kinds of controls: basic & complex
- for 3 different UI frameworks: Bootstrap 4, Material Design 2 & Ionic 2+
In the form builder we just changed 1 setting in order to select the UI framework. But there is another important setting that sets the “programming mode”: “Template driven” or “Reactive” (see arrow 2 below):
In the previous posts we always used the default setting: “Template driven”. But there is a second option for this drop-down: “Reactive forms”.
The resulting form will look exactly the same for both options. It is just that the generated code will have some differences. Below I will try to compare the 2 options.
Template driven Angular forms
Template driven is the default mechanism and resembles most with the previous Angular (v1) style of programming: html controls bind directly to your object properties (in the .ts file) by using the [(ngModel)] attribute:
Reactive Angular forms
Reactive forms on the other side are a bit more work to develop, because you need to setup a separate structure to hold your data (see the method createCustomerForm(obj) below).
So you do not bind directly with properties in your objects, instead you bind to form-controls inside a form-group:
Notice that we use the html attribute formControlName instead of [(ngModel)].
But why would you write more code if template driven is more compact and easier to write? Well it turns out that you have more control over your forms (validation is 1 example) when you use the reactive style.
The Angular Workbench allows you to generate forms in tempate driven mode or in the reactive style. Both are valid options. For small projects we advice you stick to the default template-driven method, for enterprise-grade projects we advice to evaluate both options. Anyway the forms are generated automatically, so you can always change later on!