Introduction to forms in angular

Angular forms are used to log in, update a profile, enter sensitive information, and perform many other data-entry tasks. In simple words Forms are used to handle user input data.

Angular provides two different approaches to handling user input through forms:

  • Template-Driven Approach
  • Reactive Approach

Reactive forms and template-driven forms process and manage form data differently.

1.Template-Driven Approach : Template-driven forms are suitable for small or simple forms. Template-driven forms use two-way data binding to update the data model in the component as changes are made in the template and vice versa. Controls can be added to the form using the NgModel tag. Multiple controls can be grouped using the NgControlGroup module. A form value can be generated using the “form.value” object. Form data is exported as JSON values when the submit method is called. Basic HTML validations can be used to validate the form fields. In the case of custom validations, directives can be used. You can build almost any kind of form with an Angular template—login forms, contact forms, and pretty much   any business form. You can lay out the controls creatively and bind them to the data in your object model.You can specify validation rules and display validation errors, conditionally enable or disable specific  controls, trigger built- in  visual feedback, and much more.

2. Reactive Approach : Reactive forms are more scalable and suitable for complex forms. With Reactive forms, the component directly manages the data flows between the form controls and the data models. Its a code-driven approach. Reactive forms eliminate the anti-pattern of updating the data model via two-way data binding. As Compared to template-driven forms, they are more robust , scalable, reusable, and testable. Typically, Reactive form control creation is synchronous and can be unit tested with synchronous programming techniques.

Difference between template driven approach & reactive approach:

Template-Driven Approach Reactive Approach
Template-driven forms make use of the “FormsModule” Reactive forms are based on “ReactiveFormsModule”.
Template-driven forms are asynchronous in nature Reactive forms are mostly synchronous.
In a template-driven approach, most of the logic is driven from the template. In reactive-driven approach, the logic resides mainly in the component or typescript code.

Conclusion: So this is the theoretical information about both type of forms. In next chapter will see the practical implementation of forms.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *