Form submission handling lets your app collect and use information users type in forms. It helps you respond when users click submit.
0
0
Form submission handling in Angular
Introduction
When you want to get user input like name or email.
When you need to check if the user filled the form correctly before sending data.
When you want to show a message after the user submits a form.
When you want to save user data to a server after submission.
Syntax
Angular
import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-simple-form', standalone: true, imports: [FormsModule], template: ` <form (ngSubmit)="onSubmit()" #formRef="ngForm"> <input name="username" [(ngModel)]="username" required aria-label="Username" /> <button type="submit" [disabled]="formRef.invalid">Submit</button> </form> ` }) export class SimpleFormComponent { username = ''; onSubmit() { // handle form data here } }
Use (ngSubmit) on the <form> tag to catch the submit event.
Use [(ngModel)] to bind input values to component properties.
Examples
Basic form with email input and submit button.
Angular
<form (ngSubmit)="submitForm()"> <input name="email" [(ngModel)]="email" required aria-label="Email" /> <button type="submit">Send</button> </form>
Form disables submit button if input is invalid.
Angular
<form (ngSubmit)="save()" #myForm="ngForm"> <input name="age" type="number" [(ngModel)]="age" min="1" max="120" aria-label="Age" /> <button type="submit" [disabled]="myForm.invalid">Save</button> </form>
Sample Program
This component shows a form with name and email fields. The submit button is disabled until both fields are valid. When submitted, it shows a thank you message with the entered data.
Angular
import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-user-form', standalone: true, imports: [CommonModule, FormsModule], template: ` <form (ngSubmit)="onSubmit()" #userForm="ngForm"> <label for="name">Name:</label> <input id="name" name="name" [(ngModel)]="name" required aria-label="Name" /> <label for="email">Email:</label> <input id="email" name="email" [(ngModel)]="email" required email aria-label="Email" /> <button type="submit" [disabled]="userForm.invalid">Submit</button> </form> <p *ngIf="submitted">Thank you, {{ name }}! We received your email: {{ email }}.</p> ` }) export class UserFormComponent { name = ''; email = ''; submitted = false; onSubmit() { this.submitted = true; } }
OutputSuccess
Important Notes
Always add aria-label or label elements for accessibility.
Use Angular's form validation to prevent bad data submission.
Use template reference variables like #userForm="ngForm" to check form state.
Summary
Use (ngSubmit) to handle form submission in Angular.
Bind inputs with [(ngModel)] for two-way data binding.
Disable submit button when form is invalid to improve user experience.