Two-way data-binding was a huge problem with AngularJS. Even though the concept is simple, i.e an amalgamation of property and event-binding, the implementation was rather complex. This problem was solved with the introduction of the ngModel directive in Angular 2. In this article, we will be taking a look into the ngModel directive, and how it works and makes your life as a developer so much easier:
What is ngModel?
ngModel is Angular’s answer to the two-way data binding problem. Previously in AngularJS, there was no way to perform a binding which would update automatically. This problem got addressed in angular 2 and has been working like that since then. The solution lies in the ngModel directive, which is a part of the FormsModule. Before we learn about ngModel, let’s take a brief look into what exactly is a directive.
What are Directives?
ngModel Usage with Example
The ng-model directive binds the value of HTML controls (input, select, text-area) to application data. It is a part of the FormsModule. This directive is used by itself or as part of a larger form. It accepts a domain model as an optional Input. If you have a one-way binding to ngModel with [] syntax, changing the value of the domain model in the component class sets the value in the view. If you have a two-way binding with [()] syntax (also known as ‘banana-box syntax’), the value in the UI always syncs back to the domain model in your class. To learn more about Angular ngModel, check out this Web developer course online.
The following examples show a simple standalone control using ngModel:
import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <input [(ngModel)]="name" #ctrl="ngModel" required> Value: {{ name }} Valid: {{ ctrl.valid }} <button (click)="setValue()">Set value</button> }) export class SimpleNgModelComp { name: string = ''; setValue() { this.name = 'Nancy'; } }
The above code will present you with a form which is working on two way binding. The input space and result space are tied together in a way that updates things automatically.
With this, I’d like to end my blog here. If you have any doubts or queries regarding this article please post them in the comment section below.
Take your mobile app development career to new heights with a comprehensive Flutter Training Course.
Take your design skills to the next level with our UI Design Course.
Learn about Crud Operation in Angular and NgClass
Got a question for us? Please mention it in the comments section of this “Angular ngModel” and we will get back to you.