The ngForm directive helps Angular track and manage the state of a form easily. It tells Angular to watch the form's inputs and know if the form is valid, dirty, or touched.
ngForm directive and form state in Angular
<form #formName="ngForm">
<!-- form controls here -->
</form>The #formName="ngForm" creates a local variable to access the form's state.
You can use this variable to check properties like formName.valid, formName.dirty, and formName.touched.
<form #myForm="ngForm"> <input name="email" ngModel required email /> <button [disabled]="!myForm.valid">Submit</button> </form>
<form #loginForm="ngForm"> <input name="username" ngModel required /> <input name="password" ngModel required type="password" /> <p *ngIf="loginForm.dirty && loginForm.invalid">Please fill all fields correctly.</p> <button type="submit">Login</button> </form>
This component uses ngForm to track the form state. The submit button is disabled until the form is valid. When submitted, it shows the entered data and resets the form.
import { Component } from '@angular/core'; @Component({ selector: 'app-simple-form', template: ` <form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)"> <label for="name">Name:</label> <input id="name" name="name" ngModel required /> <label for="age">Age:</label> <input id="age" name="age" ngModel type="number" required min="1" /> <button type="submit" [disabled]="!userForm.valid">Submit</button> </form> <p *ngIf="submitted"> Form Submitted! Name: {{ submittedData.name }}, Age: {{ submittedData.age }} </p> ` }) export class SimpleFormComponent { submitted = false; submittedData = { name: '', age: '' }; onSubmit(form: any) { if (form.valid) { this.submittedData = form.value; this.submitted = true; form.resetForm(); } } }
The ngForm directive automatically creates a FormGroup behind the scenes.
Use formName.resetForm() to clear the form and reset its state.
Form controls must have a name attribute for ngForm to track them.
ngForm helps Angular track form inputs and their states.
Use the local form variable to check if the form is valid, dirty, or touched.
It makes managing form validation and submission easier and cleaner.