HomeBlogWeb DevelopmentTwo-Way Data Binding in Angular with ngModel [Examples]

Two-Way Data Binding in Angular with ngModel [Examples]

Published
01st Jul, 2024
Views
view count loader
Read it in
10 Mins
In this article
    Two-Way Data Binding in Angular with ngModel [Examples]

    Angular two-way binding architecture was the one thing that made us think, "Wow." View and application state changes have been mirrored automatically. Setting a configuration value enables us to create our directives with data-bound scope attributes. 

    Angular >= 2. x does not have a built-in two-way data binding. Despite this, two-way data binding is still possible using directives. In this post, we'll look at how Angular >= 2. x does two-way data binding and how we may do it ourselves in our directives. 

    Two-way data binding is Angular applications' most often used data binding technique. The user types provide or changes any control value on one side. The same immediately updates into component variables and vice versa; the two-way data binding is utilized in the input type field or any form element. 

    Also, to know more Angular certification training is the best to go for.

    Two-way Data Binding in a Nutshell


    Both Property Binding and Event Binding are used in Angular to provide two-way data binding. The syntax is as follows: 

    Data 1 (input) = 'event.target.value' (input) 

    It's possible to use two-way data binding with angular two-way binding. x thanks to the ngModel directive. On the surface, it seems to be as miraculous as we've come to expect (from AngularJS). However, how does it function? It's not that difficult. As it turns out, two-way data binding is simply an event and a property binding. 

    Take a look at the following sample of code to see what it mean: 

    Hi, username!" is what I want to say to you. 

    Angular >= 2. x implementation of the 2009 demo blew our heads. Input is written to the username model and then mirrored back into the display, creating a friendly welcome. 

    What's going on here? Since version 2. x, two-way data binding in Angular has boiled down to property binding and event binding, as previously noted in the article. Two-way data binding does not exist. For simplicity's sake, we could have implemented two-way data binding without the ngModel directive: 

    Input value="username" (input)="username = $event.target." <p> Thank you for visiting, username>! </p> 

    Here we go: Let's take a deeper look at this situation. 

    Two-way data binding:

    • Binds input element's value to a component property (using [value]).
    • Listens for input changes (using (input)) and updates the component property with the new value ($event.target.value).

    In simpler terms, it automatically keeps the component property and input field in sync whenever there's a change.

    Now that's all well and good, but when will we need to use ngModel? Having a directive that abstracts things away and saves us a few keystrokes is a no-brainer given how often a situation like the one shown above really is. However, a good Web Development online course can be the best option for you.

    Prerequisites for Two-way Binding in Angular

    Because it is written for front-end developers of all skill levels who work with Angular, prior knowledge of the basics and the installation procedure is not expected. Angular 12 requires the following requirements before you can follow along with the example in this article: 

    • Microsoft's Visual Studio Code (VSC) 
    • You've got the latest version of Node installed on your system. 
    • Version 6.7 of the Node Package Manager (usual ships with Node installation) CLI version 8.0 or above is required. 

    Two-way binding in angular 4 is the most recent release (version 12) and uses a terminal to execute the command ng edition. To ensure that you're using the latest version, check to see whether you've already updated to 12. 

    How Two-way Binding Works?

    It turns out that the syntactic combination is not a fluke. An event binding is used in conjunction with a prettier version of a standard data binding to change the variable's value. 

    The above example may be expressed as follows: the event's name is the ngModelChange value of the input [ngModel]. 

    Even though this version is lengthier, you have more influence over what occurs. It's possible to do much more than update the "name"-variable's value when an event occurs. 

    How to Add Two-way Data Binding in Angular?

    Angular two-way binding is uncommon right out of the box. However, two-way data binding is made feasible by a widely used directive. Model is the name of the directive that implements this feature.

    NgModel must be loaded manually into your angular "FormsModule." imported NgModules from @angular/core may be found here: @angular/platform-browser BrowserModule should be imported. import '@angular/forms' from '@formsModule' './app.component' may be used to import 'AppComponent' @NgModule({[BrowserModule, FormsModule] are imported.the [AppComponent] declarations[AppComponent]: bootstrap}) 

    AppModule's class should be exported. 

    Constructing two-way data binding using NgModel and forming components like inputs is possible. A quite unusual syntax is required: [(ngModel)].. One-way and event binding are combined in this syntax. 

    This is how it's used: input name="" /> 

    In this syntax, not only is the value of the variable "name" presented as the value of the input, but both values change as the user enters the input field. 

    How to Implement Two-way Data Binding in Angular? 

    To implement two-way data binding in Angular, we use the [(ngModel)] directive and the FormsModule. This allows us to bind an input element (such as a text box or dropdown list) to a component property, allowing two-way updates.  

    Firstly, ensure that the FormsModule is imported in your Angular module: 

    import { FormsModule } from '@angular/forms'; 
    @NgModule({ 
      declarations: [ 
        // ... your components 
      ], 
      imports: [ 
        FormsModule, 
        // ... other modules 
      ], 
      // ... other metadata 
    }) 
    export class YourModule { } 
    Next, within your component HTML file, utilize [(ngModel)] to bind to a property: 
    <input type="text" [(ngModel)]="yourProperty" /> 
    Here, yourProperty is a property within your component TypeScript file that will hold the value entered in the input field. 
    In your component TypeScript file, define and utilize yourProperty: 
    import { Component } from '@angular/core'; 
    @Component({ 
      selector: 'app-your-component', 
      templateUrl: './your-component.component.html', 
      styleUrls: ['./your-component.component.css'] 
    }) 
    export class YourComponent { 
      yourProperty: string = ''; // Initialize your property 
      // Other component logic here 
    } 
    This establishes the two-way binding: changes made in the input field will reflect in the yourProperty variable, and changes to yourProperty will update the input field value automatically. 
    For more complex scenarios, custom event binding and handling may be necessary. You can use (ngModelChange) event binding to perform actions when the value changes. For instance: 
    <input type="text" [(ngModel)]="yourProperty" (ngModelChange)="onPropertyChange($event)" /> 
    In your component TypeScript file: 
    onPropertyChange(newValue: string) { 
      // Perform actions on value change 
      console.log('New value:', newValue); 
      // Additional logic here 
    } 

    This allows you to execute custom logic whenever the value of yourProperty changes. 

    Note that although two-way data binding can improve productivity, it is important to use it judiciously, as overuse can make it difficult to trace the flow of data. Finding the right balance makes your Angular application maintainable and readable.  

    The implementation of two-way data binding in Angular allows developers to create dynamic and responsive applications, creating a smoother user interaction experience. Experiment, iterate, and adapt these concepts based on your specific use cases to take full advantage of Angular's two-way data binding capabilities. 

    Understanding ngModel

    A directive in angular two way binding known as ng-model is used to connect the "view" and the "model," and its primary function is to do so. An example is a page displayed below, which asks users for their "First name" and "Last name" in text boxes to be filled up. To guarantee that the data submitted by users is stored in your data model, you also need to ensure they were. 

    You may use the ng-model directive to map the "First name" and "Last name" text box fields to your data model. For this reason, it is essential to use ng-model directives to maintain a consistent data flow between your "views" and "models." 

    The model directive uses the NgModelController to link an input, select, textarea (or custom form control) to a property on the scope. 

    ngModel is in charge of: 

    • Input, Textarea, and select all need a view to being bound to their corresponding models. 
    • It is behaving in a way that validates others (i.e., required, number, email, URL). 
    • We are maintaining the current state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). 
    • Assembling a set of associated CSS classes on the element (ng-valid/false/true/false/false/false), as well as animations (eg, ng-touched/none/none/none/none/none/none). 
    • It is adding the control to its parent form and registering it. 
    • ngModel will attempt to bind to the supplied property by evaluating the expression on the current scope. The property will be created and added to the scope implicitly if it does not already exist. 
    • ngModel's best practices may be found here: 
    • Getting a handle on Scopes 

    See these simple examples to learn the basics of working with ngModel: 

    • input 
    • text 
    • checkbox 
    • radio 
    • number 
    • email 
    • URL 
    • date 
    • DateTime-local 
    • Time 
    • month 
    • week 
    • select 
    • textarea 

    An example of two-way data binding with ngModel in Angular two will be discussed below. 

    Code in TypeScript: import the '@angular/core' component 'component' @Component({'my-app' as the selection a template for writing h3>The name's here :/ inputting "address" into a ngModel`,'./app.component.css' is the style URL.}) class AppComponent is exported. "Muhammad Adil" is his name; "Block No. 1 Sector G11, Sydney" is the address. onKeyUp() console.log(this.address)}} 

    How to Create Custom Two-way Data Bindings in Angular?

     There are no digest cycles or watchers to deal with in two-way data binding angular since two-way binding is not enabled by default. A two-way data binding between a Parent and their kid may sometimes be necessary. An example of two-way data binding is shown in this article. 

    To properly build custom two-way binding, it is necessary first to grasp the following binding concepts: 

    • Binding of properties 
    • Binding of events 

    A. Binding of Real Estate 

    Property binding refers to the practice of passing a component's data property as an attribute enclosed in square brackets [] to the target HTML element. 

    /component-a.template.html Amount: component-b [amount]="amount"> 

    It's a live property, implying that if Component A changes the property amount, Component B will also get the new values, as shown by the square bracket. Even so, it's a one-way street. Event binding is needed since Component A would not be aware of the property amount being updated by Component B. 

    B. Binding events to each other 

    Adding an event raised by another component inside parentheses () allows a component to listen in on that event. We call it Event Binding. 

    /component-a.template.html (amountChange)="doSomething()"> 

    Components might benefit from a two-way binding characteristic by combining these two features. Banana-in-a-box syntax would be [()], often referred to as that. 

    Let's look at an example of this. Provide the user an extra deposit button by creating a new ParentComponent with an amount property. The value of the amount would rise if the button were pressed. 

    @Component({ 'parent' is the selection.using the following model: 

    The primary component: 

    • It's up to you: amount>Deposit may be made by clicking a button that reads "deposit()."Deposit 100/button>`,})ParentComponent's class is exported.the amount: 500 construction(function )'s} 
    • deposit(){this.amount multiplied by one hundred;}} 
    • After that, we'll create a new ChildComponent and send the property amount to the parent. Do you recall the concept of property binding? We will use the @Input()decorator to create a property connection between the parent and child components. 
    • @Component({ 'child' is the selector. using the following model: <div> The child component: <span> Quantity at your disposal: span>amount/span> </div>`,}) Export the ChildComponent class. 
    • @Input() quantity: number} 
    • Let's alter the ParentComponent template to render the ChildComponent by utilizing its selector and sending the amount attributable to the ChildComponent. 
    • The primary component: It's up to you: amount> Deposit 100/button> To summarize, here are some examples: /child> That's all there is to it. ChildComponent will be aware of any changes to the amount when ParentComponent makes an update. 
    • A mechanism for withdrawing money from the balance and a button for the user will be included in ChildComponent. 
    • @Component({'child' is the selector. using the following model: <div> The child component: <span> 
    • Quantity at your disposal: span>amount/span> "withdraw()" is a clickable button. In order to withdraw 100 dollars, use the button /button></div>`,}) Export the ChildComponent class. @Input() quantity: number withdraw(){The value of this.amount is equal to 100}} 
    • As a result, the ChildComponent may make cash withdrawals without alerting the ParentComponent. We need to figure out how to solve it. To the rescue: Event binding! Using the @Output() decorator, we can have ChildComponent send an event whenever it changes the amount attribute. 
    • Export the ChildComponent class.@Input() quantity: numbe.AmountChange = new EventEmitter(); @Output withdraw(){The value of this.amount is equal to 100 this.amountChange.emit(this.amount);}} 
    • Once ParentComponent listens to the amount change event, it should change its amount property. 
    • The primary component:It's up to you: amount>Deposit may be made by clicking a button that reads "deposit()."Deposit 100/button> The amount of $event in this kid's account is: child [amount]="amount"> /child> 
    • When the ChildComponent changes the amount property, the new value is also reflected in the parent component. 

    The two-way binding is done! 

    Getter and Setter Methods 

    Utilizing getter and setter strategies in Angular gives you more control over information authoritative and permits you to execute extra rationale when allotting and recovering properties. These strategies give the capacity to captured property changes, perform approval, trigger occasions, or execute custom rationale.  

    Here's an example demonstrating the usage of getter and setter methods within an Angular component: 

    import { Component } from '@angular/core'; 
    @Component({ 
      selector: 'app-your-component', 
      templateUrl: './your-component.component.html', 
      styleUrls: ['./your-component.component.css'] 
    }) 
    export class YourComponent { 
      private _yourProperty: string = ''; // private backing variable 
     
      // Define getter method for your property 
      get yourProperty(): string { 
        return this._yourProperty; 
      } 
     
      // Define setter method for your property 
      set yourProperty(value: string) { 
        // You can add custom logic here before setting the value 
        if (value.length <= 10) { // Example: Perform validation 
          this._yourProperty = value; 
        } else { 
          console.error('Property length exceeds the limit.'); 
          // Handle invalid input or show error messages 
        } 
      } 
      // Other component logic here 
    } 

    In this example, the yourProperty is accessed through getter and setter methods (get and set). The underlying private variable _yourProperty holds the actual value, providing encapsulation. 

    In the component's HTML, you can bind the input field to the setter method like this: 

    <input type="text" [(ngModel)]="yourProperty" (ngModelChange)="yourProperty = $event" /> 

    You'll control the perusing and composing of properties utilizing getter and setter strategies. For occasion: 

    • Getter: This permits you to alter a esteem some time recently it is recovered by the layout or other parts of the code. You'll perform transformations or apply rationale some time recently getting to the esteem. 
    • Setter: Permits you to validate, normalize, or trigger occasions some time recently doling out a esteem to a property. You'll actualize rules or perform activities based on input values. 

    Keep in mind that getter and setter strategies offer assistance with epitome and allow you to add extra behavior by recovering or setting a property esteem. They are particularly valuable after you have to control how values are gotten to or changed in an Angular component. Utilize them admirably to progress the usefulness and viability of your code base. 

    Looking to boost your career? Learn Python, the versatile Python programming language that opens doors to endless job opportunities. Join our Python course today and unlock your potential!

    Conclusion

    In terms of functionality, angular two way data binding is unrivaled. It permits data to go back and forth between the component and the view. A user-friendly interface lets the user access and modify data stored in the database. 

    By keeping track of which UI elements are reliant on which pieces of information, data binding allows us to manage our application's state better. Changes we make in one direction automatically propagate to the other side with two-way binding, but we must manually intervene with one-way binding. 

    No two-way data binding is enabled by default in Angular 2. A simple syntax is provided for two-way data binding if it is required. KnowledgeHut’s Angular certification training course is the best option to know in depth.

    Frequently Asked Questions (FAQs)

    1What is two-way data binding Angular?

    As an Angular developer, you can utilize a two-way data binding to show the end-user information and enable them to make changes directly to the underlying database. The view (the template) and the component class are now linked in two directions. WPF's two-way binding is a good analogy for this. 

    2What is two-way data binding in Angular, for example?

    Component classes and their templates may share data using two-way binding. Changes to data at one end are immediately reflected at the other. Changing the value of an input box will also modify the value of a component class's associated attribute. 

    3Is ngModel two-way binding?

    Two-way binding of HTML Form components is achieved using the ngModel directive in the Angular framework. Form elements such as input, selection, and the selection area may be linked. 

    4How does two-way data binding work?

    Component classes and their templates may share data using two-way binding. Changes to data at one end are immediately reflected at the other. Changing the value of an input box will also modify the value of a component class's associated attribute. 

    5What is the difference between 1 way and two-way data binding?

    It's a one-way street in a one-way binding. The flow is bidirectional in a two-way bond. Code flows from a ts file to an HTML document. In other words, the code flows from the ts file to the Html file and back again. 

    6Is Angular one-way binding?

    It is possible to bind data from the component to the DOM or the other way around - from the DOM to the component. One-way data binding in Angular is called unidirectional binding. It is used to present data to the end-user that is automatically updated if the underlying data changes. 

    Profile

    Sachin Bhatnagar

    Program Director, FSD

    With 20+ yrs of industry experience in media, entertainment and web tech, Sachin brings expertise in hands-on training and developing forward-thinking, industry-centric curricula. 30k+ students have enrolled in his tech courses.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon