NgForm directive is used with HTML <form> tag. To understand NgForm, we should be aware with following classes.

FormControl : This class tracks the value and validation status of an individual form control.
FormGroup : This class tracks the value and validity state of a group of FormControl.

Now let us understand NgForm directive. NgForm is a directive that creates a top-level FormGroup instance and binds it to a form to track aggregate form value and validation status. You didn’t add an NgForm directive.

Angular did. Angular automatically creates and attaches an NgForm directive to the <form> tag.

The NgForm directive supplements the form element with additional features. It holds the controls you created for the elements with an ngModel directive and name attribute, and monitors their properties, including their validity. It also has its own valid property which is true only if every contained control is valid

Once we import FormsModule, NgForm directive becomes active by default on all <form> tags. We can export NgForm into a local template variable. To import it we need to use NgForm as ngForm. Find the sample example.

<form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">

If we use neither one-way binding not two-way binding still we need to use ngModel attribute in fields when using with parent form as given below.

Password: <input name="password" ngModel required>

To reset form, NgForm has resetForm() method that is called as follows.

<button type="button" (click)="resetUserForm(userForm)">Reset</button>

resetUserForm(userForm: NgForm) {
userForm.resetForm();;
}

We can also reset values to some default values like this :

resetUserForm(userForm: NgForm) {
userForm.resetForm({
name: 'XYZ',
Password: 'ABC'
});
}

Exporting NgForm into local template variable is optional but useful. In the above code snippet, look into #userForm=”ngForm”. Here local template variable is userForm. Using local template variable we can access form in our HTML template as following.

userForm.value: It will return form value. It means we get an object containing the values of all the fields used within <form> tag.
userForm.valid: It will return boolean value. When the value is true then form is valid. Form is said to be valid if all the fields returns validity true.
userForm.touched: It will return boolean value. If the value is true, it means user has entered value at least in one field.
userForm.submitted: It will return boolean value. If the value is true, it means form has been submitted.
userForm.dirty: It will return boolean value. It is true when something get changed in form.
userForm.pristine: It will return boolean value. It is true when something is not changed in form

Please find the working code below.

app.component.ts

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

constructor() {

}

onFormSubmit(userForm: NgForm) {
console.log(userForm.value);
console.log('Name:' + userForm.controls['name'].value);
console.log('Password:' + userForm.controls['password'].value);
console.log('Form Valid:' + userForm.valid);//true when every field submitted in form is valid
console.log('Form Submitted:' + userForm.submitted);//true when form get submitted
console.log('Form Dirty:' + userForm.dirty);//true when something get changed in form
console.log('Form Pristine:' + userForm.pristine);//true when something is not changed in form
}

resetUserForm(userForm: NgForm) {
userForm.resetForm();// used to reset the form
}
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Food</title>
<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

app.component.html

<h2>
LOGIN </h2>
<div>
<form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">
<div>
Name: <input name="name" ngModel required #userName='ngModel'>
<!--local variable userName used for getting value of name in HTML-->
</div>
<div>
Password: <input name="password" ngModel required>
</div>
<div>
<button>Submit</button>
<button type="button" (click)="resetUserForm(userForm)">Reset</button>
</div>
<div>
{{userName.valid}}--{{userName.value}}
</div>
</form>
</div>
Angular 2 NgForm with NgModel Directive
Tagged on:                         

Leave a Reply

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