All About Angular Form
Angular is a rich framework that allows us to create and use Html forms into Angular also provides a better way to validate them, so if you want to use Angular form this Article will help you.
In Angular we have following types of Angular Forms:
- TDF (Template Driven Forms).
- MDF (Model Driven Form) or Reactive Forms.
- MDF using Form Builder Service.
TDF (Template Driven Form)
As with its name, we can understand this type of form are based on Template more not on angular component, they are very easy to create and managed but not recommended for a big form or that form that form structure you have to use multiple time on different location in your app because they don’t have any dependency from angular component its completely based on HTML templates so in future if you have to change any form attributes like validations type so you have to go into your HTML and it on all the locations.
For TDF Forms we have to use ngForm to get the reference of Angular Form and will use (ngSubmit) as an Event to handle the Angular form’s submit request
Example:
Here is the Code for TDF Form with three fields (Id, Name, Salary) you can add more as per your requirement in Component.Html
<div class="container">
<form #MyForm="ngForm" (ngSubmit)="SaveData(MyForm.value)">
<div class="form-group">
<label>Id</label>
<input type="number" class="form-control col-md-3" name="Id" ngModel>
</div>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control col-md-3" name="Name" ngModel>
</div>
<div class="form-group">
<label>Salary</label>
<input type="number" class="form-control col-md-3" name="Salary" ngModel>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Save">
<button class="btn btn-danger”>Cancel</button>
</div>
</form>
</div>
Here is a Function for Component.ts that you can use as a handler with one data permeator, from where you’ll be able to get the submitted value of your angular form. Just, for an example, I try to print the value of form in console logs so check there once you submitted.
public SaveData(data:any)
{
console.log(data);
}
Now Serve your app in browser the submit the form then check once in the browser, you must be getting the expected JSON as following:
{
"Id": "101",
"Name": "Nitin Pandit",
"Salary": 1234
}
MDF (Model Driven Form)
Model-driven forms are the best way to use Angular Forms, It allows you to manage your form from your component only also you’ll be able you use to validate your Angular Form from Component. So let’s see what you have to do for this, follow the steps:
Step 1:
Import your Reactive Forms module from @angular/forms in your Module.ts file, in which module you want to use it. Like:
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
and now use this into Module metadata’s Imports:[ ], like:
imports: [
…, ReactiveFormsModule
],
Step 2:
Go to your component file and import FormsGroup and FormControl from @angular/forms, like:
import { FormGroup, FormControl } from "@angular/forms";
Now Create the object of Form Group with an object as a parameter in its constructor for the Controls that you want into the Forms like:
myForm:FormGroup=new FormGroup({
Id:new FormControl(‘’),
Name:new FormControl(''),
Salary:new FormControl(''),
Address:new FormGroup({
City:new FormControl(''),
PinCode:new FormControl('')
})
});
This Form group has four property (Id, Name, Salary, Address) where Address is a form group itself with two property (City, Pin code) now finally this form value will look like this:
{
"Id": "101",
"Name": "Nitin Pandit",
"Salary": 1234,
"Address": {
"City": "Noida",
"PinCode": 201301
}
}
Now Just create a function for handling the submitted data by a form like this:
public SaveData()
{
console.log(this.myForm.value);
}
Step 4:
Go to your component.html file and create an HTML form and bind with this FormGroup object from a component, use the following code:
<div class="container">
<h1>{{message}}</h1>
<form [formGroup]="myForm" (ngSubmit)="SaveData()">
<div class="form-group">
<label>Id</label>
<input type="number" class="form-control col-md-3" formControlName="Id" name="Id">
</div>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control col-md-3" formControlName="Name" name="Name">
</div>
<div class="form-group">
<label>Salary</label>
<input type="number" class="form-control col-md-3" formControlName="Salary" name="Salary">
</div>
<div formGroupName="Address">
<div class="form-group">
<label>City</label>
<input type="text" class="form-control col-md-3" formControlName="City" name="City">
</div>
<div class="form-group">
<label>PinCode</label>
<input type="number" class="form-control col-md-3" formControlName="PinCode" name="PinCode">
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Save">
<button class="btn btn-danger">Cancel</button>
</div>
</form>
</div>
Now Serve your app in the browser, you must be getting the following output.
Try to submit the form and check the JSON in the browser’s console, I hope you’ll find the expected JSON.
MDF using Form Builder Service
This is one more way from Angular Forms modules that can use FormBuilder Service from “@angular/forms” package, which allows you to build the form in the simplest way ever in Angular. There is no need to change anything in the last example just go and edit your component file and follow the following steps:
Step 1:
Add FormBuiledr in the import statement.
import { FormGroup,FormBuilder } from "@angular/forms";
Step 2:
Inject its object in the component constructor.
constructor(private formBuilder:FormBuilder) { }
Step 3:
Now declare an object of form group and assign this object in some function or maybe you can go ahead with ngOnInit() from component’s life cycle, like this:
myForm:FormGroup;
ngOnInit() {
this.myForm=this.formBuilder.group({
Id:[],
Name:[],
Salary:[],
Address:this.formBuilder.group({
City:[],
PinCode:[]
})
});
}
Here is the final code that you can compare with your code.
import { Component, OnInit } from '@angular/core';
import { FormGroup,FormBuilder } from "@angular/forms";
@Component({
selector: 'app-mdf-demo',
templateUrl: './mdf-demo.component.html',
styleUrls: ['./mdf-demo.component.css']
})
export class MdfDemoComponent implements OnInit {
myForm:FormGroup;
constructor(private formBuilder:FormBuilder) { }
ngOnInit() {
this.myForm=this.formBuilder.group({
Id:[],
Name:[],
Salary:[],
Address:this.formBuilder.group({
City:[],
PinCode:[]
})
});
}
public SaveData()
{
console.log(this.myForm.value);
}
}
Here in this example see you we can use FormBuilder to create angular forms.
Note: In this example, all the CSS classes are used from Bootstrap so install Bootstrap using Angular CLI. If want to learn how to use Bootstrap in Angular project from NPM using CLI, Read this Article:
How to use Bootstrap and font awesome in Angular apps?