In Angular, form controls represent the state and behavior of HTML form elements such as <input>
, <select>
, <textarea>
, etc. They are used to track and manage the value, validation status, and user interactions of these form elements within Angular's form handling mechanisms.
Types of Form Controls:
FormControl:
- Represents a single form control element.
- Tracks the value and validation status of an individual form control.
- Can be initialized with an initial value and one or more validators.
FormGroup:
- Represents a collection of form controls as a group.
- Tracks the values and validation statuses of multiple form controls together.
- Often corresponds to a section or a group of related fields in the form.
FormArray:
- Represents an array of form controls.
- Used when dealing with dynamic sets of form controls that can be added or removed dynamically.
- Each item in the array is a FormControl, FormGroup, or another FormArray.
Representation in Angular:
In Angular, form controls are represented using classes provided by the @angular/forms
module. These classes are used to instantiate and manage the state of form controls in both template-driven and reactive forms.
Example in Reactive Forms:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required]
});
}
onSubmit() {
if (this.myForm.valid) {
console.log(this.myForm.value);
// Submit logic here
}
}
}
Example in Template-Driven Forms:
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
<input type="text" name="username" ngModel required>
<input type="email" name="email" ngModel required email>
<input type="password" name="password" ngModel required>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
In both examples:
FormControl
,FormGroup
, andFormArray
instances are created and managed usingFormBuilder
in the reactive forms example.- Template-driven forms use
ngModel
to bind form controls directly to the component's properties. - Validators like
Validators.required
,Validators.email
, etc., are used to define validation rules. - The form controls (
FormControl
,FormGroup
,FormArray
) manage the state of the form elements, including their values and validation statuses.
Overall, form controls in Angular provide a structured and manageable way to work with forms, enabling validation, form submission handling, and interaction tracking in both template-driven and reactive forms.
No comments:
Write comments