Angular Two Way Data Binding

Angular Two Way Data Binding

Angular Two Way Data Binding

So far we have learned about One-Way data binding and binding properties with the event. Angular provides way much easy approach for binding which is two way data binding.

What is two way data binding

The two way data binding is the process or synchronization between View (Template) and Model (Components). In this process, any change in view will automatically be updated in model and vice versa.

Let’s see how it works with the help of below diagram.



Angular Two Way Data Binding




Writing two way data binding (Traditional Approach)

Let’s create a separate component for this example as well. Invoke the below command which will automatically create the component for you.

E:\angular\app\hello-world>ng g c two-way-data --spec false


Make sure you are running the app before creating the component.


Project Structure


Write Template

Now let’s create our view file for two way data binding.

src/app/two-way-data/two-way-data.component.html

<label>Type something ...</label>
<br />
<input 
 type="text"
 (input) = "onTypingMessage($event)"
  />
<br />
<h5>You are typing : {{message}}</h5>

Now there are some components which you need to understand here in the template file. So let’s cover them one by one.

  • (input) – It is an event which triggers on user inputs like on typing.
  • onTypingMessage($event) – It is a custom expression which will be executed on user type.
  • $event – It is a reserved variable used with event binding which gives us the access to event data.
  • {{message}} – String interpolation to display message data from component to view.

Writing the Component

Our view part is done, let’s write our component and expression which we created in our view.

src/app/two-way-data/two-way-data.component.ts


import { Component, OnInit } from '@angular/core';
@Component({
   selector: 'app-two-way-data',
   templateUrl: './two-way-data.component.html',
   styleUrls: ['./two-way-data.component.css']
})
export class TwoWayDataComponent implements OnInit {
 message: string = "";
 constructor() { }
 ngOnInit() { }
 onTypingMessage(event: Event) {
   this.message = (<HTMLInputElement> event.target).value;
 }
}

As you can see in above example, we have create two things in our component. Let’s cover them one by one.

  • message: string – This is our new property in which we will store user inputs.
  • onTypingMessage(event: Event) – We have created a function which accepts argument of type Event because we are passing event variable from our view. This variable will provides us the access to the event data.
  • <HTMLInputElement> – The HTMLInputElement interface provides special properties and methods for manipulating the layout and presentation of input elements.
  • event.target – We are type casting our target to <HTMLInputElement> so that we can invoke it’s methods and properties like value.

Invoke the Component

As your component is already registered with the application module, we can directly invoke the newly created component as below.

src/app/app.component.html

<app-two-way-data></app-two-way-data>

You will see the action as below.


two way data binding



But there is much simpler approach to do so in angular with the help of property binding. Let’s see that in action.


Modify the View

Angular framework provides us a special Directive which does the same work as we did earlier but with less coding.

src/app/two-way-binding/two-way-binding.component.html

<label>Type something ...</label>
<br />
<input 
 type="text"
 [(ngModel)]="message"
  />
<br />
<h5>You are typing : {{message}}</h5>

As you can see in the above template, we are combining both property and event with the special syntax “[( )]” followed by the Directive name “ngModel”.

The above directive will bind the component property with the input event so you don’t need to write event separately.


Modify the Component

Now if we don’t need to write any event expression manually, we can remove the method from the component class.

src/app/two-way-binding/two-way-binding.component.ts


import { Component, OnInit } from '@angular/core';
@Component({
 selector: 'app-two-way-data',
 templateUrl: './two-way-data.component.html',
 styleUrls: ['./two-way-data.component.css']
})
export class TwoWayDataComponent implements OnInit {
 message: string = "";
 constructor() { }
 ngOnInit() { }
}

Note*: In order to use “ngModel”, the FormsModule from ‘@angular/forms’ should be added to your imports in your app module as below.

src/app/app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

//Should be imported for 'ngModel'
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
import { ItemListComponent } from './item-list/item-list.component';
import { AngBindingComponent } from './ang-binding/ang-binding.component';
import { EventBindingComponent } from './event-binding/event-binding.component';
import { TwoWayDataComponent } from './two-way-data/two-way-data.component';
@NgModule({
 declarations: [
  AppComponent,
  ItemListComponent,
  AngBindingComponent,
  EventBindingComponent,
  TwoWayDataComponent
 ],
 imports: [
  BrowserModule,
  FormsModule 
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

Now run the app and it should work same.


two way data binding
two way data binding

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *