</>
Skip to content
Angular lessons (19/43)

Angular — Forms

Template-Driven Forms

import { FormsModule } from '@angular/forms';

@Component({
  imports: [FormsModule],
  template: `
    <form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
      <input name="email" ngModel required email>
      <input name="password" ngModel required minlength="6">
      <button [disabled]="loginForm.invalid">Login</button>
    </form>
  `
})
export class LoginComponent {
  onSubmit(form: any) {
    console.log(form.value);
  }
}

Reactive Forms

import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';

@Component({
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="email">
      <input formControlName="password">
      <button [disabled]="form.invalid">Login</button>
    </form>
  `
})
export class LoginComponent {
  form = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [Validators.required, Validators.minLength(6)])
  });
  
  onSubmit() {
    console.log(this.form.value);
  }
}

Form Validation

// Template-driven
// In template: *ngIf="email.invalid && email.touched"

// Reactive
this.form.get('email')?.invalid

Mini Practice

  1. Create a template-driven form
  2. Create a reactive form
  3. Add validation
  4. Handle form submission

Up Next

Continue with Form Validation — validating form inputs.

Related Topics

Frequently Asked Questions about Forms

What is Forms in Angular?

Forms is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Forms?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Forms.

Why is Forms important in Angular?

Forms is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.