Data Binding To A Model In Angular

Introduction
 
When we have the UI form ready in Angular, then we need to send the data to the server for further operations. Simply, we can send it to save the details. But before we send the data to the server, we have to first bind the data to the model. Let us see how.
 
Before we start with data binding to the model, we must have a form created. Click here to see how we can create a form with data binding using a template-driven approach applied to it.
 
Create a new class.
  • >ng generate class Address
  • >ng generate class Student
Open address.ts and add the below code.
  1. export class Address {  
  2.     constructor(  
  3.         public street: string,  
  4.         public city: string,  
  5.         public state: string  
  6.     ){}  
  7. }  
Open student.ts and add the below content.
  1. import { Address } from "./address";  
  2.   
  3. export class Student {  
  4.     constructor(  
  5.         public name: string,  
  6.         public email: string,  
  7.         public phone: number,  
  8.         public gender: string,  
  9.         public course: string,  
  10.         public sendUpdates: boolean,  
  11.         public bloodGroup: string,  
  12.         public address: Address  
  13.     ){}  
  14. }  
We are using TypeScript shorthand syntax for defining the constructor. The compiler of TypeScript generates a public key for each public parameter and assigns the value to the field when you create the instance. It is similar to the services that we inject to the constructor.
 
We have created the model. Now, we have to create an instance.
 
Open app.component.ts and add the below code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Student } from './student';  
  3. import { Address } from './address';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css']  
  9. })  
  10. export class AppComponent implements OnInit{  
  11.   groups=['A+''A-''B+''B-''O+''O-'];  
  12.     
  13.   addressModel = new Address("Lukerganj""Allahabad""UP");  
  14.   studentModel = new Student("Mohammad Irshad""[email protected]",  7878787878, "male""MCA"true"A+"this.addressModel)  
  15.   
  16.   SubmitDetails(studentData){  
  17.     console.log(studentData);  
  18.   }  
  19.   constructor() { }    
  20.   ngOnInit() {    
  21.   }  
  22. }  
We will try to bind the studentModel data to our created form. We will bind this value to the form and update through the UI form.
Let us first try to bind this value to the student form.
 
How will the value of the model be bound to the form?
 
We are simply binding the properties of the model to the ngModel directive. For property binding, we will use square brackets []. For binding, replace ngModel to [ngModel].
 
Eg: for property ‘name’ binding
 
[ngModel]=”studentModel.name”

We have a studentModel having ‘name’ property that we are binding to the ‘name’ input element.

The above [ngModel] used will only bind the data one way because property data binding is one-way binding. It will only bind the data from the class to the View but not from View to the class model.
 
When we want the two-way binding, then we have to use the below binding technique.
 
Change the [ngModel] to the [(ngModel)] to make it a two-way bind.
 
Open app.component.html and add the below code.
  1. <div class="container-fluid">  
  2. <h3>  
  3.   Student Registration!  
  4. </h3>  
  5. <p>Enter the below fields for student details.</p>  
  6.   <form #studentForm="ngForm" (ngSubmit)="SubmitDetails(studentForm.value)">  
  7.     <div class="row">  
  8.       <div class="col-sm-4">  
  9.           <div class="form-group">  
  10.               <label for="name">Name:</label>  
  11.               <input type="text" class="form-control" [(ngModel)]="studentModel.name" name="name">  
  12.             </div>  
  13.       </div>  
  14.       <div class="col-sm-4">  
  15.           <div class="form-group">  
  16.               <label for="email">Email address:</label>  
  17.               <input type="text" class="form-control" [(ngModel)]="studentModel.email" name="email">  
  18.             </div>  
  19.       </div>  
  20.       <div class="col-sm-4">  
  21.           <div class="form-group">  
  22.               <label for="phone">Phone:</label>  
  23.               <input type="text" class="form-control" [(ngModel)]="studentModel.phone" name="phone">  
  24.             </div>  
  25.       </div>  
  26.     </div>  
  27.     <div class="row">  
  28.         <div class="col-sm-4">  
  29.             <div class="form-group">  
  30.                 <label for="gender">gender:</label>  
  31.                 <input type="text" class="form-control" [(ngModel)]="studentModel.gender" name="gender">  
  32.               </div>  
  33.         </div>  
  34.         <div class="col-sm-4">  
  35.             <div class="form-group">  
  36.                 <label for="bloodGroup">Blood Group:</label>  
  37.                 <select class="form-control" [(ngModel)]="studentModel.bloodGroup" name="bloodGroup">  
  38.                   <option selected="">A+</option>  
  39.                   <option *ngFor="let group of groups">{{group}}</option>  
  40.                 </select>  
  41.               </div>  
  42.         </div>  
  43.         <div class="col-sm-4">  
  44.             <div class="form-group">  
  45.               <label>Course </label><br>  
  46.               <input type="radio" [(ngModel)]="studentModel.course" name="course" value="BCA">BCA     
  47.               <input type="radio" [(ngModel)]="studentModel.course" name="course" value="B.Tech">B.Tech     
  48.               <input type="radio" [(ngModel)]="studentModel.course" name="course" value="BE">BE     
  49.               <input type="radio" [(ngModel)]="studentModel.course" name="course" value="B.Sc">B.Sc     
  50.             </div>  
  51.         </div>          
  52.     </div>  
  53.     <div class="row" ngModelGroup="address">  
  54.         <div class="col-sm-4">  
  55.             <div class="form-group">  
  56.                 <label>Street</label>  
  57.                 <input type="text" class="form-control" name="street" [(ngModel)]="studentModel.address.street">  
  58.               </div>  
  59.         </div>  
  60.         <div class="col-sm-4">  
  61.             <div class="form-group">  
  62.                 <label>City</label>  
  63.                 <input type="text" class="form-control" name="city" [(ngModel)]="studentModel.address.city">  
  64.               </div>  
  65.         </div>  
  66.         <div class="col-sm-4">  
  67.             <div class="form-group">  
  68.                 <label>State</label>  
  69.                 <input type="text" class="form-control" name="state" [(ngModel)]="studentModel.address.state">  
  70.               </div>  
  71.         </div>  
  72.     </div>  
  73.     <div class="checkbox">  
  74.       <label><input type="checkbox" [(ngModel)]="studentModel.sendUpdates" name="sendUpdates"> send me updates</label>  
  75.     </div>  
  76.     <button type="submit" class="btn btn-primary">Submit</button>  
  77.      
  78.   </form>  
  79. </div>  
  80. <br>  
  81. <h5>StudentForm value:</h5>  
  82. {{studentForm.value | json}}  
  83. <h5>StudentModel value:</h5>  
  84. {{studentModel | json}}  
In the above code, we are showing you the value of form: via {{studentForm.value | json}} and the value of studentModel via {{studentModel | json}}
 
Run the application.
 
 Data Binding To A Model In Angular
 
You can see the details filled via studentModel.
 
Data Binding To A Model In Angular 
Right now the value of studentForm and studentModel are same.
 
Let us change the values in the form.
 
Data Binding To A Model In Angular 
You can see the changes reflect in both ways in form as well as in model.
 
Data Binding To A Model In Angular 
 
This is how you can achieve the two-way binding from UI to model and model to UI through its binding.
 
Now, change all the [(ngModel)] to [ngModel] in file app.component.html property binding and see what happens.
 
Run the application.
 
You will see the first behavior will be the same as the model value will be bind as it is to the UI form.
 
Now, make any update in the UI form input.
 
Data Binding To A Model In Angular 
Data Binding To A Model In Angular 
 
You can see that  the values of form are updated but the value of the model is not updated because this time we have used property binding, which is one-way binding, and UI to model updation does not happen.
 
So, with the help of two-way binding, we can capture the data of the form to the model and send to server and also, we can perform important validations and visual checks and error message display to the form before sending it to the server.


Similar Articles