2
votes

I would like to know when should I use a template driven form instead of a Reactive form. I know the theory based in that question(What are the practical differences between template-driven and reactive forms?) but I don't know which one use with Angular Material. I always have doubts about which use.

Could anyone help me please?

Thank you in advance.

2

2 Answers

2
votes

As an Angular focused developer I recommend always using reactive form setups.

Developers will argue but trust me you will be saving yourself headaches later. Netanel B wrote about it here too: Why It’s Time to Say Goodbye to Angular Template-Driven Forms

Let's say you want a very simple input, you may be tempted to simply use

  • ngModel
  • template variables
  • @ViewChild

They may be fine, for now.

But let's say you need to add:

  • Validation
  • Watching for changes
  • Updating the value programmatically

These all require you rely on and code around the method you've chosen to access the input.

Where Reactive forms are a pre-built API which brings a standard to each need.

2
votes

Template-driven forms

  • Use template-driven forms when developing static forms. Static means the structure and logic of a form is fix. E.g. the number of form fields does not vary, form validation rules are the same for different user roles, etc.
  • Examples are login forms, reset password forms, forms to enter and edit address data, order data and similar fix data structures.

Reactive-forms

  • Use the reactive forms approach in case the form shall support dynamic data structures and logic. Examples are dynamic survey forms, forms to add/delete 0..n tags or phone numbers, forms providing different validation for different user roles, etc.

  • The structure and logic of reactive forms is mainly implemented in TypeScript. Corresponding HTML artifacts only refer to the form controls defined in TypeScript. At highest expansion stage a reactive form can be entirely generated at runtime based on a data structure.

For more detail you can refer the follow this link