How to implement guide with dynamic form field validation in angular reactive forms with async validators
I've tried everything I can think of but I've encountered a strange issue with I'm stuck on something that should probably be simple... I'm working with a question with validating dynamic form fields in Angular using Reactive Forms, specifically when using async validators. I have a form that allows users to add multiple email addresses, and I want to ensure that each email is unique across the entire form. When the user adds a new email, I call an async validator that checks against existing entries in the backend. However, the validation seems to be inconsistent. Here's a simplified version of my form setup: ```typescript import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms'; import { debounceTime, switchMap } from 'rxjs/operators'; import { EmailService } from './email.service'; @Component({ selector: 'app-email-form', templateUrl: './email-form.component.html', }) export class EmailFormComponent implements OnInit { emailForm: FormGroup; constructor(private fb: FormBuilder, private emailService: EmailService) { this.emailForm = this.fb.group({ emails: this.fb.array([]), }); } ngOnInit() {} get emails(): FormArray { return this.emailForm.get('emails') as FormArray; } addEmail() { const emailGroup = this.fb.group({ email: ['', [Validators.required, Validators.email], [this.uniqueEmailValidator.bind(this)]], }); this.emails.push(emailGroup); } uniqueEmailValidator(control: FormControl) { return control.valueChanges.pipe( debounceTime(300), switchMap(value => this.emailService.checkEmailUnique(value)), ); } } ``` The `EmailService.checkEmailUnique` function makes an HTTP request to the backend and returns an observable that emits `null` if the email is unique, or an object with an behavior message if it's not. However, when I add new emails, sometimes I see the validation errors not updating in time, leading to false positives or negatives. I also noticed that when I remove an email, the form doesn't seem to revalidate correctly. Is there a best practice for handling dynamic fields with async validators in Angular? Are there known issues with the validation lifecycle that I might be missing? Any insight would be greatly appreciated! I'm using Angular 12 and RxJS 7.0. Thanks! This is part of a larger web app I'm building. Any ideas what could be causing this? Any examples would be super helpful. I'm working on a mobile app that needs to handle this. Is this even possible? I'm working with Typescript in a Docker container on Windows 11. I'm open to any suggestions.