0% found this document useful (0 votes)
3 views

Types of Angular Forms

Angular offers two types of forms: Template Driven Forms, which simplify data binding using ngModel with minimal code, and Reactive Forms, which require explicit form control creation and validation in the component class. Template Driven Forms are ideal for simple forms, while Reactive Forms are better suited for complex scenarios involving dynamic controls and validations. The document provides implementation steps for both form types, including examples of registration forms and the necessary Angular module imports.

Uploaded by

dixitharsh052004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Types of Angular Forms

Angular offers two types of forms: Template Driven Forms, which simplify data binding using ngModel with minimal code, and Reactive Forms, which require explicit form control creation and validation in the component class. Template Driven Forms are ideal for simple forms, while Reactive Forms are better suited for complex scenarios involving dynamic controls and validations. The document provides implementation steps for both form types, including examples of registration forms and the necessary Angular module imports.

Uploaded by

dixitharsh052004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Angular Forms

Angular provides us with two types of forms:

1. Template Driven Forms


2. Reactive Forms

In Template Driven Forms, you create controls on the component template and bind data
using ngModel. With these, you do not create controls, form objects, or write code to work
with pushing and pulling of data between component class and template; Angular does all of
these tasks for you. In template driven forms, there is very little code for validations in the
component class, and they’re asynchronous.

In order to use Template Driven Forms, we need to import FormsModule into the application
root module i.e. app.module.ts file.

Template Driven Forms are used to bind the data to the component class using ngModel. We
do not need to take the pain of writing code and most of the task is done by Angular itself.
There is very less of effort required from the developer to pass information from the component
class to the template.

In Reactive Forms, you create form controls as trees of objects in the component class and
bind them to the native form controls in the template. All validations and the creation of form
controls are written in the component class. In Reactive Forms, all validations and changes in
the state of native forms are synchronous, so you can write code in the component class to
observe them. You should choose to create reactive forms when the data model is immutable
and usually mapped to a database.

In a model driven approach, the model which is created in the .ts file is responsible for handling
all the user interactions and validations. For this, first, we need to create the model using
Angular’s inbuilt classes like formGroup and formControl and then we need to bind that model
to the HTML form.

Reactive forms are synchronous and are usually considered when working with databases. We
write the code for validation inside the component class and also map the objects to the form
controls on the view.
Using Reactive forms, we will be able to create and manipulate various form-control objects
directly into the component itself. because the component class has all the access to the form
control structure and the data model, so we can push model values into the form controls and
also be able to check for the updated values that have been changed by the end-user.

The major difference between these two approaches of creating forms? In reactive forms you
do not use directives such as ngModel, required, etc. You create all controls and their
validations in the component class. Reactive forms are easy to test and maintain

Which one is better – Template Driven or Reactive Forms?


Neither reactive nor template driven are better over each other. For example, Template Driven
forms are generally used to create simple forms. On the other hand, Reactive forms are used to
create complex forms. For example, if you want to add form controls dynamically or perform
cross-field validation, then you need to use the Reactive forms approach.

Implementation:

How we can develop and use Template forms in Angular Application?

Step1: Importing Forms module

The ngForm directive is provided by Angular FormsModule. So, first we need to import the
Forms module in the applications root module i.e. in the app.module.ts file

we are doing two things. First the import the FormsModule from the angular library and then
declare the FormsModule in the import array of the @NgModule decorator.
Step2: Create a Registration Form

We want to create a registration form to register a student.


Modifying app.component.html file:
In order to create the above registration form, please modify the app.component.html file

Here, we are using Bootstrap CSS classes like panel, panel-primary, panel-heading, panel-title
etc. to style the form.

<br/>
<div class="container">
<div class="row">
<div class="form-bg">
<form #studentForm="ngForm" (ngSubmit)="RegisterStudent(studentForm)">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Student Registration</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="firstName">First Name</label>
<input id="firstName" type="text" class="form-control"
name="firstName" ngModel>
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input id="lastName" type="text" class="form-control"
name="lastName" ngModel>
</div>
<div class="form-group">
<label for="email">Email</label>
<input id="email" type="text" class="form-control"
name="email" ngModel>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>

As you can see in the above code, we have created three text boxes and one button. But along
with we are using something called NgForm, NgMoel, and many more things.

NgForm:
It is the directive which helps to create the control groups inside form directive. It is attached
to the <form> element in HTML and supplements from tag with some additional features.
NgModel:

When we add ngModel directive to the control, all the input elements are registered with the
NgForm. It created the instance of the FormControl class from Domain model and assign it to
the form control elements. The control keeps track of the user information and the state and the
validation status of the form control.

Next important thing is to consider is that when we use ngModel with form tag, then we should
have to use the name property of the HTML control.
Two main functionalities are provided by NgForm and NgModel are the permission to
retrieving the values of the control associated with the form and then retrieving the overall state
of the controls in the form.

#studentForm is called the template reference variable and if you notice we have assigned
“ngForm” as the value for the template reference variable studentForm. So the studentForm
reference variable holds a reference to the form.

The form tag is not associated with any action method, then the question is how we post the
form data to the component. The answer is using ngSubmit directive.

Understanding ngSubmit directive:

Please have a look at the following ngSubmit directive. Here, we are using the Event Binding
concept and we binding to the RegisterStudent method of the component. Instead of the submit
event of the form, we are using ngSubmit which will send the actual HTTP request instead of
just submitting the form.

The ngSubmit directive will submits the form when we either hit the enter key or when we
click the Submit button. When the form is submitted, RegisterStudent() method of the
AppComponent class is called and we are passing it the studentForm. We do not have this
method at the moment in the AppComponent class. We will create this method.

Step3: Creating RegisterStudent() method


Now, open app.component.ts file and then copy and paste the below code in it. As you can see
here, we created the RegisterStudent method. At the moment, we are simply logging the value
of the Angular generated Form model to the console. In order to use the NgForm in our
component class, first we need to import NgForm type from ‘@angular/forms‘.

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


import { NgForm } from '@angular/forms'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
RegisterStudent(studentForm: NgForm): void {
console.log(studentForm.value);
}
}

As we already discussed, The ngForm directive supplements the form element with additional
features and properties like value, dirty, touched, valid etc. In the above example, we use the
value property, similarly you can also use the other properties. These properties are very useful
for form validations.

How we can develop and use Reactive forms in Angular Application?


Step 1: Import ReactiveFormsModule in App Module
Step 2: Import FormControl, FormGroup classes in the component class
Step 3: Create a FormGroup class with details like email, password
Step 4: On the template, create a Submit button with the function to implement submit in the
class.

app.component.ts

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


import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';

export class AppComponent implements OnInit {


loginForm: FormGroup;
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl(null, [Validators.required, Validators.minLength(4)]),
password: new FormControl(null, [Validators.required, Validators.maxLength(8)])
});
}
loginUser() {
console.log(this.loginForm.status);
console.log(this.loginForm.value);
}
}

app.component.html

<form (ngSubmit)='loginUser()' [formGroup]='loginForm' novalidate class="form">


<input formControlName='email' type="text" class="form-control" placeholder="Enter Email" />
<div class="alert alert-danger" *ngIf="loginForm.get('email').hasError('required') &&
loginForm.get('email').touched">
Email is required
</div>
<input formControlName='password' type="password" class="form-control" placeholder="Enter
Password" />
<div class="alert alert-danger" *ngIf="!loginForm.get('password').valid &&
loginForm.get('email').touched">
Password is required and should less than or equal to 8 characters
</div>
<button [disabled]='loginForm.invalid' class="btn btn-default">Login</button>
</form>

Example 2:

A reactive form should have at least one form group. It is called the root form group.

The root form group contains the properties to keep the states, default values, and properties to
retain the user inputs and set of FormControls for each input field.

We can use the formGroup and formControl to create the form model.

We can follow the below steps to create the formModel


1. Open the app.module file
2. Import the ReactiveFormsModule from @angular/forms and add the
ReactiveFormsModule into the import array.

3. Open the component file


4. Create a property ‘userForm’ of type FormGroup.

This property will be the reference to the form model

5. Import the FormGroup class from ‘@angular/forms’.

Next, we need to assign the 'userForm' property to the new instance of the FormGroup.

We will do it in the 'ngOnInit' life cycle hook.

Here, we are using the ngOnInit life cycle hook instead of the constructor.

This is because we need to make sure that the component and template are initialized before
creating the form Model.
As you can see in the above screenshot, in the FormGroup constructor we are passing an object
as a parameter.

We can use this parameter to pass the FromControls and nested FormGroups as key-value pairs

We need to create FormControls for the name, emailID, gender, payment type, and notification.

Also, import the FormControl from ‘@angular\forms’

We have created the basics of the model successfully.

Open app.component.html
Here, the ‘formGroup’ directive is used to bind the form element in the template to the root
form group of the form model

<form [formGroup]="userForm">

‘userForm’ is the form model property defined in the component class.

Link the template and form model

The next step is to connect each input controls in the registration form to the properties of the form
model.

We already linked the root form group of the form model to the form element in the template using
‘formGroup’ directive.

So the form model properties will be available inside the template.

We can bind each form model properties to the input controls using the ‘formControlName’ directive.
Here, the 'name' and 'email' are the form control properties defined inside the component class.

I have added the 'formControlName' directive to all the input elements and added the 'ngSubmit event
binding to save the user data.
On clicking the Register button, saveData() method will be executed.

Inside the saveData() method, I’m just writing the form mode values to the console.

But, we can write any other code logic to save the user data.

Save the project and fill the form and click the ‘Register’ button.

Open the developer console window to see the user data in the form model.
Visit website for more details:

https://dotnettutorials.net/lesson/angular-forms/

https://www.c-sharpcorner.com/article/lets-develop-an-angular-application-angular-
reactive-forms/

Note:

ngOnInit is a life cycle hook called by Angular to indicate that the Angular is done creating the
component. In order to use OnInit we have to import it in the component class like this: import
{Component, OnInit} from '@angular/core'; Actually implementing OnInit in every
component is not mandatory.

You might also like