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:
-
Template-driven forms
- Use directives in the template (
ngModel,ngForm). - Simpler approach suitable for small forms.
- Validation and form logic are described in HTML.
- Use directives in the template (
-
Reactive forms
- Manage the form in the component through
FormGroup,FormControlobjects. - Allow more flexible control over state and validation.
- Better suited for complex forms with dynamic elements.
- Manage the form in the component through
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.