0
0
Angularframework~5 mins

FormsModule setup in Angular

Choose your learning style9 modes available
Introduction

FormsModule helps you easily create and manage forms in Angular apps. It makes handling user input simple and organized.

You want to collect user information like name and email.
You need to validate form inputs before sending data.
You want to react to user changes in form fields.
You want to bind form inputs to component variables.
You want to build simple forms without complex setup.
Syntax
Angular
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  standalone: true,
  imports: [FormsModule],
  selector: 'app-example',
  template: `
    <input [(ngModel)]="name" placeholder="Enter name">
    <p>Hello, {{ name }}!</p>
  `
})
export class ExampleComponent {
  name = '';
}

Always import FormsModule in your standalone component's imports array.

Use [(ngModel)] to bind input fields to component properties for two-way data binding.

Examples
This example shows a simple input bound to email property using FormsModule.
Angular
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  standalone: true,
  imports: [FormsModule],
  selector: 'app-simple-form',
  template: `
    <input [(ngModel)]="email" placeholder="Email">
    <p>Your email is: {{ email }}</p>
  `
})
export class SimpleFormComponent {
  email = '';
}
This example binds a number input to the age property.
Angular
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  standalone: true,
  imports: [FormsModule],
  selector: 'app-age-form',
  template: `
    <label for="age">Age:</label>
    <input id="age" type="number" [(ngModel)]="age">
    <p>You are {{ age }} years old.</p>
  `
})
export class AgeFormComponent {
  age = 0;
}
Sample Program

This component uses FormsModule to bind the input field to the username property. When the user types, the greeting updates automatically.

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

@Component({
  standalone: true,
  imports: [FormsModule],
  selector: 'app-user-form',
  template: `
    <h2>User Form</h2>
    <label for="username">Username:</label>
    <input id="username" [(ngModel)]="username" placeholder="Enter username">
    <p>Hello, {{ username || 'guest' }}!</p>
  `
})
export class UserFormComponent {
  username = '';
}
OutputSuccess
Important Notes

Without importing FormsModule, ngModel will not work and Angular will show an error.

Use standalone components with imports array to keep your code simple and modular.

Summary

Import FormsModule to use form features in Angular.

Use [(ngModel)] for two-way binding between inputs and component data.

Standalone components make setup easy by listing FormsModule in imports.