Sobes.tech
Middle

What are the classic approaches to working with forms in Angular?

sobes.tech AI

Answer from AI

In Angular, there are two classic approaches to working with forms:

  1. Template-driven forms

    • Use directives in the template (ngModel, ngForm).
    • Simpler approach suitable for small forms.
    • Validation and form logic are described in HTML.
  2. Reactive forms

    • Manage the form in the component through FormGroup, FormControl objects.
    • Allow more flexible control over state and validation.
    • Better suited for complex forms with dynamic elements.

Example of a reactive form:

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

this.form = new FormGroup({
  username: new FormControl('', [Validators.required, Validators.minLength(3)]),
  email: new FormControl('', [Validators.required, Validators.email])
});

In the template:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input formControlName="username">
  <input formControlName="email">
  <button type="submit">Submit</button>
</form>

The choice of approach depends on the complexity of the task and team preferences.

What are the classic approaches to working with forms… - sobes.tech