Angular Forms NgForm Directive

In this tutorial, we’ll look at what NgForm is in Angular 10 and how to utilise it. NgForm is used to build a top-level form group Instance and ties the form to the specified form value.

This directive becomes enabled by default on all tags as soon as you import the FormsModule. There is no need to include a specific selection.
You may additionally export the directive into a local template variable with the key ngForm (for example, #myForm=”ngForm”). This is optional yet beneficial. Many attributes from the underlying FormGroup instance are mirrored on the directive, so a reference to it provides you access to the form’s aggregate value and validity status, as well as user interaction properties like dirty and touched.
Use NgModel with a name property to register child controls with the form. NgModelGroup may be used to construct sub-groups within the form.

Listen to the directive’s ngSubmit event if necessary to be alerted when the user triggers a form submission. The initial form submission event is emitted by the ngSubmit event.
All tags in template-driven forms are automatically marked as NgForm. To import the FormsModule but not use it in some forms, such as to utilise native HTML5 validation, add the ngNoForm and the tags will not construct a NgForm directive. Because the tags in reactive forms are inactive, using ngNoForm is unnecessary. You would avoid using the formGroup directive in such situation.

Syntax:

<form #FormName = "ngForm"> </form>

NgModule: Module used by NgForm is:

  • FormsModule

Selectors:

  • [ngForm]

Make the Angular app that will be utilised.
FormsModule should be imported into app.module.ts.
Create a form in app.component.html, save its value in the ngForm variable, and display it in a JSON form.
To see the result, run the angular app with ng serve.

File name :- App-module.ts

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';


import { AppComponent } from './app.component';

@NgModule({
bootstrap: [
  AppComponent
],
declarations: [
  AppComponent
],
imports: [
  FormsModule,
  BrowserModule,
  BrowserAnimationsModule,
  
]
})
export class AppModule { }

File name :- App-component.ts

<form #gfgform = "ngForm">
{{ gfgform.value | json }}
<br>
<br>
Name: <input type="text" name = 'name' ngModel>
Email: <input type="email" name = 'email' ngModel>
</form>

Submit a Comment

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

Subscribe

Select Categories