05. Forms in Angular
π Master Angular forms! This tutorial covers Template-driven, Reactive Forms, custom validators, and dynamic forms, empowering you to build robust and efficient user interfaces. Learn to create powerful forms in Angular and boost your development skills! π
What we will learn in this post?
- π Template-driven Forms
- π Reactive Forms
- π Custom Validators
- π Dynamic Forms
- π Conclusion!
Error: An error occurred while processing your request. Please try again later.
Error: An error occurred while processing your request. Please try again later.
Custom Validators in Angular Forms π
Angularβs built-in validators are great, but sometimes you need more control. Letβs explore creating custom validators for both template-driven and reactive forms.
Template-Driven Forms π
Creating a Custom Validator
In template-driven forms, we create a custom validator function that returns an error object or null
. This function receives the AbstractControl
as input.
1
2
3
4
5
6
7
8
// my-validator.ts
export function myValidator(control: AbstractControl): ValidationErrors | null {
const value = control.value
if (value && value.length < 5) {
return { minLength: true } // Custom error key
}
return null
}
Then, apply it in your template:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<input
type="text"
[ngModel]="myValue"
name="myInput"
required
(ngModelChange)="myForm.controls.myInput.markAsTouched()"
[ngModelOptions]="{standalone: true}"
[validator]="myValidator"
/>
<div
*ngIf="myForm.controls.myInput.touched && myForm.controls.myInput.errors?.minLength"
>
Input must be at least 5 characters long!
</div>
More info on template-driven forms
Reactive Forms π
Implementing Custom Validators
In reactive forms, you can define validators directly within your FormGroup
or FormControl
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// my-reactive-form.component.ts
import {
AbstractControl,
FormControl,
FormGroup,
Validators,
} from "@angular/forms"
import { myValidator } from "./my-validator"
export class MyReactiveFormComponent {
myForm = new FormGroup({
myInput: new FormControl("", [Validators.required, myValidator]), //apply built in and custom validators
})
}
And then in your template:
1
2
3
4
5
6
7
8
9
<form [formGroup]="myForm">
<input type="text" formControlName="myInput" />
<div
*ngIf="myForm.get('myInput')?.touched && myForm.get('myInput')?.errors?.minLength"
>
Input must be at least 5 characters!
</div>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
Remember to import Validators
and AbstractControl
from @angular/forms
. Choose the approach that best fits your projectβs structure and complexity. Enjoy building robust and customizable forms! β¨
Dynamic Forms in Angular: Mastering FormArrays and FormGroups π
Creating dynamic forms in Angular, where the number of fields changes based on user interaction, is super easy using FormArrays
and FormGroups
. Letβs dive in!
Understanding FormArrays β
FormArrays
are perfect for representing a list of similar items. Think of a form where users can add multiple addresses, hobbies, or skills. Each item in the array is a separate FormGroup
.
Example: Adding Hobbies
Imagine a form where users can add as many hobbies as they like. Youβd use a FormArray
to handle this. Hereβs a simplified representation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
this.hobbyForm = this.fb.group({
hobbies: this.fb.array([this.createHobby()]) // Start with at least one hobby
});
createHobby(): FormGroup {
return this.fb.group({
name: ['', Validators.required]
});
}
addHobby() {
this.hobbies.push(this.createHobby()); // Add a new hobby
}
get hobbies(): FormArray {
return this.hobbyForm.get('hobbies') as FormArray;
}
This code creates a FormArray
named hobbies
. The addHobby
function adds new FormGroup
elements representing individual hobbies.
Working with FormGroups π§±
FormGroups
are used to group related form controls together. They are essential building blocks for complex forms. Each FormGroup
can have its own set of validators and controls.
Example: Contact Details
For contact details, you might use a FormGroup
:
1
2
3
4
5
this.contactForm = this.fb.group({
name: ["", Validators.required],
email: ["", Validators.email],
phone: ["", Validators.pattern("\\d{10}")],
})
Use Cases β¨
- Adding multiple addresses: Use a
FormArray
ofFormGroups
, each representing an address with fields like street, city, state, etc. - Building questionnaires: Dynamically add questions based on previous answers.
- Managing shopping carts: Each item in the cart can be a
FormGroup
.
Further Learning π
- Angular Reactive Forms Documentation: The official Angular documentation provides comprehensive guidance.
Remember to install the @angular/forms
module in your Angular project! This will enable you to use all the fantastic features described above. Using FormArrays
and FormGroups
unlocks the power to create truly dynamic and user-friendly forms in your Angular applications. Happy coding!
Conclusion
So there you have it! We hope you enjoyed this read and found it helpful π. Weβre always looking to improve, so weβd love to hear your thoughts! What did you think of this post? Do you have any questions, suggestions, or even just want to share your own experiences? Let us know in the comments below! π We canβt wait to chat with you! π€