Angular ngModel is a directive from FormsModule that creates a FormControl instance from the domain model and binds it to a form control element. It bridges the gap between model(component class) and view(html template).
The ngmodel directive binds the value of HTML controls (input, select, textarea) to application data. It is used for two-way data binding.
What is two-way data binding in Angular?
Two-way data binding in Angular is a mechanism that allows the synchronization of data between the model (component class) and the view (html template). This means any changes in the UI elements (like input fields) automatically update the corresponding property in the component, and any changes in the component’s property automatically reflect in the UI elements.
Two-way binding uses the syntax [()] or bind- keyword. This synchronization between the model (the application’s data/state) and the view (UI) makes ngModel a robust tool for developing dynamic and interactive applications.
In Angular, the ngModel directive, part of the FormsModule, primarily facilitates two-way data binding.
The ngModel directive is simple to use and requires minimal setup. It is straightforward to integrate into any template-driven form in Angular.
Here is a step-by-step guide:
Step 1: Setup Angular 18
To create a new Angular 18 project, you must install Angular CLI 18 on your machine.
After installing Angular CLI, you can create a new project using the below command:
ng new ngmodel-app
Go inside the project and open it in your favorite code editor.
cd ngmodel-app
Step 2: Import FormsModule
Import FormsModule and add it to the AppComponent’s imports list.
Modify the src/app/app.component.ts file like this:
import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-root', standalone: true, imports: [FormsModule, RouterOutlet], templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { data: string = ''; }
Once the FormsModule is imported, you can use the ngModel directive in your template to establish two-way binding.
We also defined a data variable, which is a type string.
Step 3: Binding [(ngModel)]
Add an [(ngModel)] binding on an HTML <form> element and set it equal to the property; here it is data.
Add the following code in the src/app/app.component.html file:
<div> <label for="exampleInput">Example Input:</label> <input type="text" id="exampleInput" [(ngModel)]="data" /> </div> <p>Input Value: {{ data }}</p>
We are also displaying the data property.
So, here, two-way data binding is at work. When the user types anything in the textbox, it will display as an input value.
Step 4: Run the project
Type the following command to start the development server:
ng serve --open
That’s all!
Mario Luiz
Tenks,
This tutorial helps me a lot.
Krunal
Your welcome. Keep learning and sharing.