How To Create Form In Angular

How To Create Form In Angular

The data is collected from the user using Angular forms. In this article, we will learn about what is Angular Forms, and then we will examine how to use Angular Forms with sample examples in the following article.

Data entry forms can range from simple to sophisticated. It can have a big number of input fields that span numerous tabs. Complex validation logic dependent on many fields may also be present in forms.

There are some things that forms are required to do.

  • Set up the form fields and show them to the user.
  • Obtain information from the user.
  • Keep track of the modifications you've made to the fields.
  • Validate the data.
  • Show the user helpful errors.

Angular Forms Module

All of the above services are available out of the box with the Angular forms module. It connects the Angular component class to the form field. It keeps track of changes to the form fields so we can respond appropriately. Validators are built-in to Angular forms to ensure that inputs are correct. You can make your own custom validator from scratch. It shows the user the validation errors. When the user submits the form, it encapsulates all of the input fields into an object structure.

The forms are built in two ways by Angular. One way is template-driven forms, while the other is reactive forms or model-driven forms.

Template-driven forms approach

The simplest method to create Angular forms is to use a template-driven approach. The form's logic is stored in the template. This is a similar approach to what we used in AngularJs.

Model-driven forms approach

The logic of the form is defined in the component as an object in the Reactive Forms or Model-driven method. The model-driven method has greater advantages because it simplifies component testing.

The form's representation is built in the component class in this technique. The HTML elements are then bound to this form model. It's done with the use of specific markups.

With Agular template-driven forms, we can easily design sophisticated-looking forms without having to write any javascript code. Form fields are produced as properties of our component class, and model-driven forms are created in the component class. This makes testing a lot easier.

Building Blocks of Angular Forms

Regardless of whether you're use Template-driven or Reactive forms, the Angular Forms module is made up of three building components.


FormControl

In an Angular form, FormControl represents a single input field.

Take a look at a simple Text input box.

First Name : <input type="text" name="firstname" />

As a developer, you'd like to know what the Text box's current value is. You'd also like to know whether the value is correct. If the value(dirty) has been updated by the user or if it has remained unchanged. You'd like to be notified whenever the user's value changes.

The FormControl is an object that contains all of the data associated with a single input element. It keeps track of the value and validity of each of these controls.

FormControl is merely a class. For each form field, a FormControl is produced. We may use our component class to refer to them and check their attributes and methods.

FormControl can be used to set the value of a Form field, as well as to determine the status of a Form field.
let firstname= new FormControl(); //Creating a FormControl in a Reactive forms

The value property can then be used to access the current value in the input field.
firstname.value   //Returns the value of the first name field

The validity status of the First Name element can be checked as shown below.
firstname.errors      // returns the list of errors
firstname.dirty       // true if the value has changed (dirty)
firstname.touched     // true if input field is touched
firstname.valid       // true if the input value has passed all the validation

FormGroup

A FormGroup is a group of FormControls. A FormGroup FormControl is a property. with the key being the control name

Many forms feature many fields. It's useful to have a simple way to manage all of the Form controls at the same time.

Consider the Form below. There are three fields to fill out: street, city, and pincode.
city : <input type="text" name="city" >
Street : <input type="text" name="street" >
PinCode : <input type="text" name="pincode" >

Each of the input fields shown above is represented by a single FormControl. If we wanted to make sure our form was legitimate, we had to check the validity of each and every FormControl. Consider a Form with a huge number of fields. It's inconvenient to check the validity of a large number of FormControls in a loop.

FormGroup solves this problem by wrapping a set of FormControls in a wrapper interface. Each child FormControl state is tracked by a FormGroup, which aggregates the values into a single object. with the key being the name of each control

As illustrated below, we can group these input fields under the group address.
let address= new FormGroup({
    street : new FormControl(""),
    city : new FormControl(""),
    pinCode : new FormControl("")
})

The address in the preceding example is our FormGroup, which is made up of three Form Controls: city, street, and Pincode. We can now examine the legitimacy of the entire group as a whole. If the state is invalid, for example, the address FormGroup will return the invalid state.

The value method, which returns a JSON object as illustrated below, can be used to read the value of an address.
address.value

The Return value
address {
    street :"",
    city:"",
    Pincode:""
}

you can access to child control as.
address.get("street")

Check the status of validation as follows:
address.errors     // returns the list of errors
address.dirty      // true if the value of one of the child control has changed (dirty)
address.touched    // true if one of the child control is touched
address.valid      // true if all the child controls passed the validation

There can be several FormGroups in an Angular Form. Another FormGroup can be contained within a FormGroup.

The Angular form is a FormGroup in and of itself.

FormArray

An array of form controls is known as a FormArray. Except for one exception, it's very identical to FormGroup. Each FormControl is a property in FormGroup, with the control name as the key. FormArray is a collection of form controls.

The FormArray is defined as follows:
contactForm = new FormGroup( {
  name: new FormControl(''),
  cities:new FormArray([
    new FormControl('Mumbai'),
    new FormControl('Delhi')
  ])
});

The contactForm can provide you with the city references. method to obtain
cities() :FormArray {
  return this.contactForm.get("cities") as FormArray
}

Check the status of validation as follows:
cities.errors     // returns the list of errors
cities.dirty      // true if the value of one of the child control has changed (dirty)
cities.touched    // true if one of the child control is touched
cities.valid      // true if all the child controls passed the validation

Conclusion

We learned what Angular Forms is all about in this article. The basic building pieces of Angular Forms, FormGroupFormControl, and FormArray, were examined. We can use two distinct techniques to develop Forms using Angular. Template-driven is one, and Reactive Forms or Model-driven is another.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post