ngModel is an Angular directive that simplifies two-way data binding on form elements. It synchronizes an element’s value with a component property: changes in either direction are reflected immediately. section 2.6 section 13.3.1
Use ngModel to connect form controls to application state:
- Write [(ngModel)]="item.complete" to bind a checkbox to an item’s boolean property. section 2.6
- Write [(ngModel)]="newProduct.name" to update a nested property as the user types. section 13.4.1
- Use FormsModule to enable the form features required by ngModel. section 13.3.1
- Remember that [( and )] combine property and event binding; Angular calls this syntax banana-in-a-box. section 13.3.1
Editing a product through form controls
Bind each input to the corresponding property, then pass the updated object to a click handler: <input [(ngModel)]="newProduct.name" /> <input [(ngModel)]="newProduct.category" /> <input [(ngModel)]="newProduct.price" /> <button (click)="addProduct(newProduct)">Create</button>. Interpolation can display the JSON representation immediately, making changes visible before the button is clicked. section 13.4.1
Listing 13.14. Replacing the contents of the template.html file in the src/app folder
<div class="p-2">
<div class="bg-info text-white mb-2 p-2">
Model Data: {{jsonProduct}}
</div>
<div class="form-group">
<label>Name</label>
<input class="form-control" [(ngModel)]="newProduct.name" />
</div>
<div class="form-group">
<label>Category</label>
<input class="form-control" [(ngModel)]="newProduct.category" />
</div>
<div class="form-group">
<label>Price</label>
<input class="form-control" [(ngModel)]="newProduct.price" />
</div>
<button class="btn btn-primary mt-2" (click)="addProduct(newProduct)">
Create
</button>
</div>
Inspect a complete template that binds several form inputs to a Product object and submits it through a component method. section 13.4.1
Listing 13.12. Using the ngModel directive in the template.html file in the src/app folder
<div class="p-2">
<div class="bg-info text-white p-2">
Selected Product: {{ selectedProduct() ?? '(None)' }}
</div>
<table class="table table-sm table-bordered">
<tr *ngFor="let item of products(); let i = index"
[class.bg-info]="getSelected(item)">
<td (mouseover)="selectedProduct.set(item.name)">
{{i + 1}}
</td>
<td>{{item.name}}</td>
<td>{{item.category}}</td>
<td>{{item.price}}</td>
</tr>
</table>
<div class="form-group">
<label>Product Name</label>
<input class="form-control" [(ngModel)]="selectedProductProp" />
</div>
<div class="form-group">
<label>Product Name</label>
<input class="form-control" [(ngModel)]="selectedProductProp" />
</div>
</div>
Inspect ngModel replacing separate property and event bindings, including a getter-and-setter bridge for a signal. section 13.3.1

