Angular 2: Iterate over reactive form controls
Found out that Object.keys
can handle this..
Object.keys(this.form.controls).forEach(key => {
this.form.get(key).markAsDirty();
});
For Angular 8+, use the following (based on Michelangelo answer):
Object.keys(this.form.controls).forEach(key => {
this.form.controls[key].markAsDirty();
});
For what it's worth, there's another way to do this without having to use Object.keys(...) magic:
for (const field in this.form.controls) { // 'field' is a string
const control = this.form.get(field); // 'control' is a FormControl
}
The accepted answer is correct for a flat form structure, but does not completely answer the original question. A web page may require nested FormGroups and FormArrays, and we must account for this to create a robust solution.
public markControlsDirty(group: FormGroup | FormArray): void {
Object.keys(group.controls).forEach((key: string) => {
const abstractControl = group.controls[key];
if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
this.markControlsDirty(abstractControl);
} else {
abstractControl.markAsDirty();
}
});
}
Seems that get
function is not working anymore for retrieving specific values in your form in Angular 8, so this is how I solved it based on the answer of @Liviu Ilea.
for (const field in this.myForm.controls) { // 'field' is a string
console.log(this.myForm.controls[field].value);
}
Using @Marcos answer I created a function that can be called passing a formGroup as parameter and it marks every formGroup children controls to dirty, just to make it usable from more places around the code putting it inside a service, for example.
public touchAllFormFields(formGroup: FormGroup): void {
Object.keys(formGroup.controls).forEach((key) => {
formGroup.get(key).markAsDirty();
});
}
hope it helps ;)