Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Angular Forms

Forms are a fundamental part of web applications, allowing users to interact with the application by submitting data. Angular provides robust support for building and managing forms with its template-driven and reactive form approaches. This tutorial provides an overview of Angular forms, their key features, and how to create and use them effectively.

Types of Angular Forms

Angular supports two main types of forms:

  • Template-Driven Forms: These forms are defined using Angular's template syntax and directives. They are simple to use and suitable for basic use cases.
  • Reactive Forms: These forms are defined using Angular's reactive programming approach. They provide more control and flexibility, making them suitable for complex use cases.

Template-Driven Forms

Template-driven forms are defined using Angular's template syntax and directives. Here is an example of a simple template-driven form:

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" ngModel required>
  </div>
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" ngModel required email>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>

<pre>{{ myForm.value | json }}</pre>

Reactive Forms

Reactive forms are defined using Angular's reactive programming approach. Here is an example of a simple reactive form:

// Component class
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-reactive-form',
  templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
}

// Component template
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="myForm.get('name').invalid && myForm.get('name').touched">
      Name is required
    </div>
  </div>
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="myForm.get('email').invalid && myForm.get('email').touched">
      Valid email is required
    </div>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>

<pre>{{ myForm.value | json }}</pre>

Validation

Angular provides built-in validators for common use cases, such as required fields, email format, and minimum/maximum length. You can also create custom validators for more complex validation logic.

// Custom validator
import { AbstractControl, ValidatorFn } from '@angular/forms';

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const forbidden = nameRe.test(control.value);
    return forbidden ? {'forbiddenName': {value: control.value}} : null;
  };
}

// Using custom validator
this.myForm = this.fb.group({
  name: ['', [Validators.required, forbiddenNameValidator(/admin/i)]],
  email: ['', [Validators.required, Validators.email]]
});

Conclusion

Angular forms provide a powerful and flexible way to build and manage forms in your applications. By understanding and using template-driven and reactive forms, along with built-in and custom validators, you can create robust and user-friendly forms for your Angular applications. Happy coding!