In this post we will see how to do data binding in two ways using angular. For this functionality we will do following task
1. Creating an array to store the Emp record.
2. add a default Emp record to Emp array.
3. Creating the Emp properties in typescript
4. Creating a method for saving the Emp record
Step 1 : Now we will go the Emp.Component.ts file and add all required code like this
import { Component, OnInit } from '@angular/core'; // Emp class in typescript export class Emp { empId: number; emailId: string; mobileNum: number; address: string; } @Component({ selector: 'app-emp', templateUrl: './emp.component.html', styleUrls: ['./emp.component.css'] }) //Initalization of Emp properties export class EmpComponent implements OnInit { empId: number; emailId: string; mobileNum: number; address: string; emps: Emp[]; // Adding the default value to emp array constructor() { this.ClearEmpData(); let defaultEmp: Emp = { empId: 2000, emailId: "Chandradev@gmail.com", mobileNum: 9241503288, address: "Bangalore" }; this.emps = [defaultEmp]; } ngOnInit() { } //Storing the value in Emp Array CreateEmp(){ let newEmp : Emp= { empId:this.empId, emailId:this.emailId, mobileNum:this.mobileNum, address:this.address }; this.emps.push(newEmp); this.ClearEmpData(); } // This is for clearing the Emp values private ClearEmpData() { this.empId = null; this.emailId = ''; this.mobileNum = null; this.address = ''; } }
Step 2: Go to the Emp.Component.html file write the data binding code like this
<div> <fieldset> <legend> <b> Emp Details</b></legend> <ul *ngFor="let i of emps" > <span> EmpId: {{i.empId}} <br> </span> <span>Emp EmailId: {{i.emailId}} <br> </span> <span> Emp Mobile Num: {{i.mobileNum}} <br></span> <span> Emp Address: {{i.address}} </span> </ul> </fieldset> </div> <div> <fieldset> <legend> <b> Emp Entry Screen with two way data binding demo</b></legend> <label> {{ empId }} </label> <div> <b>EmpId:</b> <input [(ngModel)]="empId" placeholder="enter empId"> </div> <br> <label> {{ emailId }} </label> <div> <b>Email Id:</b> <input [(ngModel)]="emailId" placeholder="enter emp EmailId"> </div> <br> <label> {{ mobileNum }} </label> <div> <b>Mobile Number:</b> <input [(ngModel)]="mobileNum" placeholder="enter mobile Number"> </div> <br> <label> {{ address }} </label> <div> <b>Emp Address:</b> <input [(ngModel)]="address" placeholder="enter address"> </div><br> <br> <button class="btn" (click)="CreateEmp()"> Save </button> </fieldset> </div>
in the above code we saw that we are displaying the data from array using *ngFor angular loop. We have also create a form for accepting the input and adding in Emp array.
>> We have use [(ngModel)] directive for doing two way data binding.
>> 2 curly braces {{ }} are used to bind values to view or template
>> (click) is used to add click handler
Step 3: Go to the app.module.ts file and write the code to import FormsModule as give below image
Step 4: Now save and compile the code in Visual studio code.