Angular FormControl vs ngModel

Asked on October 20, 2023
What is difference between Angular FormControl and ngModel? What are the preferable conditions to use FormControl over ngModel?

Replied on November 03, 2023

1. FormControl 

FormControl is used in reactive form application. It binds a HTML element with TypeScript class property.
TypeScript code:

name = new FormControl();

HTML template code:

<input [formControl]="name"> 

To control a HTML form, Angular uses FormGroup. Form group is the collection of FormControl and FormArray. 
Find the code snippet to create a form group with form controls.

empForm = new FormGroup({
   name: new FormControl('',   Validators.maxLength(10)),
   age: new FormControl('',   Validators.required)

HTML code:

<form [formGroup]="empForm" (ngSubmit)="onFormSubmit()">
   Name:  <input formControlName="name">
    Age:  <input formControlName="age">

2. NgModel

NgModel is used in template-driven form. NgModel binds an element with TypeScript class property.
Suppose we have a property in TypeScript class as below.

name = ''

Bind it to HTML template as below.

<input [(ngModel)]="name">

It is two-way binding. Value changed in property will reflect in HTML and value changed in HTML will reflect in property.

ngModel can also be used to access value and validation status in HTML template.

<input [(ngModel)]="name" #empName="ngModel">

<p>{{ name }}</p>
<p>{{ empName.value }}</p>
<p>{{ empName.valid }}</p> 

Find the code snippet to create a HTML form using ngModel.

<form #empForm="ngForm" (ngSubmit)="onFormSubmit(empForm)">
  Name: <input [(ngModel)]="name">
  Age: <input [(ngModel)]="age">

Write Answer

©2024 | Privacy Policy | Contact Us