Post

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! πŸš€

05. Forms in Angular

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>

More info on reactive forms

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 of FormGroups, 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 πŸš€

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! πŸ€—

This post is licensed under CC BY 4.0 by the author.