No, they are not equivalent. Here's the breakdown:
1. Different Purposes:
control.markAsDirty(): Marks a control as "dirty" (i.e., the user has modified its value).
markAllAsTouched(): Marks all controls (including nested ones) as "touched" (i.e., the user has blurred/unfocused the control).
2. Recursion:
markAllAsTouched() recursively marks all nested controls (e.g., controls inside FormGroups or FormArrays) as touched.
- Your
forEach loop only marks top-level controls as dirty. Nested controls are ignored.
3. Coverage:
markAllAsTouched() handles the entire form tree.
- The
forEach loop only processes direct children of this.promotionForm.
Equivalent to markAllAsTouched():
If you want to manually mark all controls (including nested) as touched, you'd need a recursive function:
markAllTouched(control: AbstractControl): void {
if (control instanceof FormGroup || control instanceof FormArray) {
Object.values(control.controls).forEach(child => this.markAllTouched(child));
} else {
control.markAsTouched();
}
}
// Usage
this.markAllTouched(this.promotionForm);
Equivalent to markAllAsDirty() (Angular 14+):
If you want to mark all controls as dirty (including nested), use Angular 14+'s built-in:
this.promotionForm.markAllAsDirty(); // Recursive dirty marking
For Angular <14, use a recursive function similar to the one above, but with markAsDirty().
Key Takeaways:
| Approach | Marks As | Recursive? | Angular Version |
|---|
control.markAsDirty() (loop) | Dirty | ❌ | All |
this.promotionForm.markAllAsTouched() | Touched | ✅ | All (built-in) |
this.promotionForm.markAllAsDirty() | Dirty | ✅ | Angular 14+ |
Summary:
Use markAllAsTouched() for recursive touched marking.
For dirty marking, upgrade to Angular 14+ and use markAllAsDirty(), or implement recursion manually.