Two way binding in Angular is achieved by ngModel.
If ngModel is used it becomes template driven form. If you are using Angular 2, ngModel can also be used in ReactiveForms, but as of in Angular 6 the usage of ngModel in ReactiveForms is removed.
ngModel directive comes with the FormsModule. If FormsModule is not included you will see the following error. Import the FormsModule from @angular/forms in AppModule to use the ngModel directive.
Can't bind to 'ngModel' since it isn't a known property of 'input'.
- There is no directive with "exportAs" set to "ngModel"
To solve this error import FormsModule in AppModule.
ngModel is used to bind template input field to component variable. The binding is two way. If component variable is updated it will reflect in form field and form field value is updated it will reflect in component instance variable.
Here ngModel is explained with a Single Component. Import FormsModule in AppModule to use ngModel directive in component.
NgModelComponent
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: ` <div>
<h1>{{title}}</h1>
<table>
<th>Item</th><th class="alignment">Amount</th><th class="alignment">Qty</th><th>Total</th>
<tr>
<td>Apple</td>
<td><input [(ngModel)]="amount" name="amount" style="width:70px;" required></td>
<td><input [(ngModel)]="qty" name="qty" type="number" style="width:70px;" required></td>
<td>$:{{amount * qty | number : '1.2-2'}}</td>
<td><button>Delete</button></td>
</tr>
</table>
<button style="margin-left:20%" (click)="getQuantity()">Print Quantity</button>
</div> `,
styles: ['div { background: azure;padding: 100px; } .alignment{text-align:center;}']
})
export class NgModelComponent {
title = 'Angular ngModel Example ';
amount: number = 10;
qty: number = 0;
getQuantity(){
console.log('Updated Quantity :' + this.qty);
}
}
To understand, amount is set as 10 in component variable and it will be updated in form input amount field. quantity in component variable is initialized with zero and if form value is changed it will be updated in component variable. Change quantity in form and on clicking Print Quantity button, the updated quantity will be printed in console.
I hope the ngModel is more clear to you now on reading this topic.