Wednesday, October 18, 2023

Two Way DataBinding Sample Example

Synchronizing data between component and template is called "two way databinding"

*Example:

price -100------------------->textbox-100 (input [value]="price" >---?property binding
                                                now textbox is edited
   <------------200 [ input    (input) = "price  =$event.target.value">  ]
                                                                           eventbinding

*two way databinding is a combination of property binding and event binding
*whenever textbox is edited,input event will be executed
*$event is an event handler,which will provide complete details of an event
 occured[includes controlname,..]
*$event.target will provide access to the control to which an event as
 occurred the above case it will be textbox control,textbox property value
 can be used to read textbox data



The two-way data binding is basically used in the input type filed or any form 
element where the user type or provide any value or change any control value on 
the one side and on the other side, the same automatically updated into the 
component variables and vice-versa is also true.

Example

create a component



.ts 

import { Component } from '@angular/core';

@Component({
  selector: 'app-twowaydatabinding',
  templateUrl: './twowaydatabinding.component.html',
  styleUrls: ['./twowaydatabinding.component.css']
})
export class TwowaydatabindingComponent {
  username:string="xxxxx";

  m1(event:Event)
  {
    this.username=(event.target as HTMLInputElement).value;
  }
}

.html

<div style="font-size:x-large;margin:20px">
    enter username:<input type="text" [value]="username" (input)="m1($event)">
    <br>
    Hi,{{username}}
</div>


From the above code, we need to understand two things.(Property Binding)

  1. <input [value]=’username’>: it binds the component class “username” property to the value property of the input element.
  2. Hi, {{Name}}: The Interpolation displays the value we have in the “username” property of the Component class on the web page.
So, Initially when you browse the output is



















At this moment if you change the value in the textbox, then that changed value is not going to be reflected in the browser (i.e. in the second line i.e. after you entered string). There are two different mechanisms that you can use to make them reflected (i.e. two-way data binding).


From the above code, we also need to understand about event binding

Let’s understand the above code  

  1. [value]=’username: This is property binding and it flows the data from the component class Name property to element property i.e. value property of the input element.
  2. (input)=’username= $event.target.value’: This is event binding and it flows the data in the opposite direction i.e. from the element to the component class property i.e. “username”
  3. $event: It is provided by angular event binding and it contains the event data. To retrieve the values from the input element, you need to use it as – $event.target.value.
  4. username= $event.target.value: This expression updates the value in the Name property of the component class
  5. Hi: {{username}}: This interpolation expression will then display the updated value on the web page.

*event.target will provide generic html element, it should be type casted
 to html input element[textbox],value prop can be used to read textbox data

    (event.target as Htmlinputelement).value



Angular12+ makes strict type casting by default, this requires explicit
 type casting[done above]

*developer can remove strict type casting by setting an option in
 tsconfig.json
    ->goto explorer window and select tsconfig.json
                   ...
       "compilerOptions":{
                         ...
                 "strict":false [default is true]
                         ...
                        }
        "angularCompilerOptions":{
                           ...
               "strictTemplates":false  [   "  ]
                           ..
                                }

     


Now, two way data binding can also achieve using ngModel 

*this is used to implement twoway databinding
*syntax:
  <tagname [(ngModel)]="varname">
           |        |
       property +  event
       binding     binding

*ngmodel will implement property binding and event binding automatically
*ngModel can be applied to input,textarea and select tags
*ngModel directive comes with FormsModule

 FormsModule                       AppModule
    |                                 |
 ngModel directive   ------------->imports:[FormsModule]
                                   components---> <input [(ngModel)]="varname">


Now, let us change the above code to ngModel as below

<input type="text" [value]="username" (input)="m1($event)">

to

<input [(ngModel)]='username'>


IF , we run this we will get an error, because ngModel is available in FormsModule, so we need to import that in appmodule.ts as shown below



















.html changes

<div style="font-size:x-large;margin:20px">
    enter username: <input [(ngModel)]='username'>
    <br>
    Hi,{{username}}
</div>


Output











Example

.ts changes
















.html changes




















No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...