0
0
Angularframework~5 mins

ngModel for form binding in Angular

Choose your learning style9 modes available
Introduction

ngModel helps connect form inputs to your component data easily. It keeps the input and data in sync automatically.

When you want to update your component data as the user types in a form input.
When you want to show the current value of a variable inside an input field.
When you want to handle simple forms without writing extra event handlers.
When you want two-way data binding between your form and component.
When you want to validate or react to user input changes easily.
Syntax
Angular
<input [(ngModel)]="propertyName" />

The [(ngModel)] syntax is called two-way binding. It means the input updates the property and the property updates the input.

You must import FormsModule in your Angular module to use ngModel.

Examples
Binds the input value to the username property in the component.
Angular
<input [(ngModel)]="username" />
Binds the input to the email property inside a user object.
Angular
<input [(ngModel)]="user.email" />
Binds a number input to the age property.
Angular
<input [(ngModel)]="age" type="number" />
Sample Program

This component has an input bound to the name property using ngModel. As you type, the greeting updates automatically.

Angular
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-user-form',
  template: `
    <label for="name">Name:</label>
    <input id="name" [(ngModel)]="name" aria-label="User name input" />
    <p>Hello, {{ name }}!</p>
  `
})
export class UserFormComponent {
  name = '';
}
OutputSuccess
Important Notes

Always add aria-label or use <label> for accessibility.

ngModel works best for simple forms. For complex forms, consider Reactive Forms.

Remember to import FormsModule in your module to enable ngModel.

Summary

ngModel creates two-way binding between form inputs and component data.

It updates the component property when the user types and updates the input if the property changes.

Use it for simple, quick form bindings with minimal code.