Forms in Angular

Posted By : Krishna Jangir | 02-Feb-2021

Introduction

 

Forms in Angular enable users to work with user inputs like login, register, save, update, and may other also.

There are two ways through which we can handle the user inputs in Angular: reactive forms and template-driven forms. Both capture user input events from the view andvalidate the user input, create a form model and data model to update the values.

 

Reactive Forms

 

Reactive forms are more scalable, testable, reusable, and ver effective to work on. If you build employment which involve more reactiveness, then use reactive forms of Angular to build applications.

Let's consider an example where we are setting up the Reactive forms that are using the form model FormControl instance we can see above example for that.

Filename: example.component.ts

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-example',
  template: `
    Example input: <input type="text" [formControl]="exampleControl">
  `
})
export class ExampleComponent {
  exampleControl = new FormControl('');
}

 

Also Read: Introduction to Typescript and Javascript

 

Template-Driven Forms

 

Template-driven forms are not as scalable as Reactive forms presents. If you want a very basic form requirement and logic that can be managed solely in the template, use template-driven forms.

Let's consider an example for a template-driven form where we are binding the text value exampleText to the input element , can see blow example.

Filename: example.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-template-example',
  template: `
    Example Text: <input type="text" [(ngModel)]="exampleText">
  `
})
export class ExampleComponent {
  exampleText = '';
}

 

From this guide, you will be able to identify which form type to choose based on the requirement .

 

Key Differences Between Reactive Forms and Template-Driven Forms:

  • The data model in reactive forms is more structured than template-driven forms as mentioned.

  • Reactive forms are synchronous in nature, whereas template-driven forms are asynchronous in nature.

  • Form validations in reactive forms are handled through functions, whereas in template-driven forms and they are handled through directives and also validate the forms.

  • Reactive forms are immutable in nature, whereas template-driven forms are mutable in nature and very useful.

  • Reactive forms are more explicit and created in the component class element and template-driven forms are very less explicit  makes our site  more dynamic.

 

Also Read: Angular Components And Their Working Methodologies

 

Building Blocks of Angular Forms

 

  • FormControl control instance tracks the value and validation status of an individual form control and make a controller for the data.

  • FormGroup control instance tracks the same values and status for a collection of form controls and create group for the data.

  • FormArray control instance tracks the same values and status for an array of form controls and handle array based data.

  • ControlValueAccessor control instance creates a bridge between Angular FormControl instances and native DOM elements and control the errors and validations .

 

Forms in Angular use a form model to keep track of value changes between Angular forms and form input elements and also provide validation for the forms in very efficient way.

 

Data Flow in Angular Forms

Data flow in Angular is handled differently in both the reactive and template-driven forms and both support data flow.

The data flow examples below begin with the example text input field example from above,  and data binding handle by formcontrol name and then show how changes to example text are handled in reactive forms compared to template-driven forms and reactive forms are much scalable than template.

 

Data Flow in Reactive Forms

Updates or changes from the view (or DOM) to the model and from the model to the html are synchronous and aren't dependent on the UI rendering of data and data flow work is different in both forms. 

Let's consider an example shown below and go through the steps of data flow in reactive forms and after will see template forms's flow.

Filename: example.component.ts

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-example',
  template: `
    Example input: <input type="text" [formControl]="exampleControl">
  `
})
export class ExampleComponent {
  exampleControl = new FormControl('');
}

 

The steps below describe the data flow from view to model.

  • The user types a value into the input element, in this case, the text value says "Hello World".
  • The form input element emits an "input" event with the latest value and that show two way binding.
  • The control value accessor listening for events on the form input element immediately relays the new value to the FormControl instance and changes fetch by ngonchanges method.
  • The FormControl instance emits the new value through the valueChanges observable and emit the values.
  • Any subscribers to the valueChanges observable receive the new value and fetch the new value.

 

The steps below outline the data flow from model to view and steps are below.

  • The user calls the exampleControl.setValue() method is very useful, which updates the FormControl value.
  • The FormControl instance will emits the new value  through the valueChanges observable.
  • Any subscribers to the valueChanges observable will receive new values.
  • The control value accessor on the form input element will updates the element with the new value.

 

Also Read: Overview Of Angular version 10

 

Data Flow in Template-Driven Forms

In template-driven forms, each forms element is connected with a directive that  will manages the form model internally.

Filename: example.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-template-example',
  template: `
    Example Text: <input type="text" [(ngModel)]="exampleText">
  `
})
export class ExampleComponent {
  exampleText = '';
}

 

The steps below outline the data flow from view to model and followed are the steps.

  • The user types "Hello World" into the input element and ngModel is also used to do two way binding.
  • The input element emits an "input" event with the value "hello Krishna".
  • The control value accessor attached to the input triggers the setValue() method on the FormControl instance and setValue() is used to set the values.
  • The FormControl instance emits the new value through the valueChanges observable and ngonchanges methos we can fetch.
  • Any subscribers to the valueChanges observable will receive new values.
  • The control value accessor also calls the NgModel.viewToModelUpdate() method which emits an ngModelChange event both are usable to update the form value.
  • Because the component template uses two-way data binding for the exampleText property, the below exampleText property in the component is updated to the value emitted by the ngModelChange event .

 

The steps below describe the data flow.

  • The exampleText value is updated in the component.
  • Change detection begins.
  • During change detection, the ngOnChanges lifecycle hook is called on the NgModel directive instance value because the value of one of its inputs has changed .
  • The ngOnChanges() method queues an async task to set the value for the internal FormControl instance.
  • Change detection completes.
  • On the next tick, the task to set the FormControl instance value was executed .
  • The FormControl instance emits the latest value through the change observable .
  • Any subscribers to the valueChanges observable receive the new value as user input.
  • The control value accessor updates the form input  value and element in the view with the latest exampleText value.

 

Form Validation in Angular

Validation is one of the important parts of forms for security and other reasons for that validation is important. Angular provides a set of built-in validators as well as the ability to create custom validators and validatores methos.

  • In reactive forms, validations are handled through custom validators as functions that receive control to validate and there are many for patterns also.
  • In template-driven forms validations are handled through directives and must provide custom validator directives that wrap validation functions.

 

Also Read: A Brief Overview of The Angular Framework

 

Conclusion

We have explored the forms in angular and we saw different types of forms like reactive and template-driven forms and all the difference between the both forms.

 

Turn To Our SaaS App Development Services

 

We are a 360-degree software development company that provides cross-platform SaaS app development services to address varied software project requirements. We have an experienced team of Java, PHP, and Python developers who use advanced frameworks, tools, and SDKs to build scalable web and mobile applications with custom features. For more detail, reach us out at [email protected].

About Author

Author Image
Krishna Jangir

She has skills on JavaScript frameworks like ionic , angular 4+ and basic knowledge on html, css. She is fond of learning and explore the things.

Request for Proposal

Name is required

Comment is required

Sending message..