I am working on creating a group of nested forms, as shown in https://plnkr.co/edit/c93yFe2r83cvjiRvl6Uj?p=preview .
This is an example fork from https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#reactive
An example in Angular shows the use of validationMessages when a form does not have nest groups. I'm not sure how to expand this when I have nested form groups. Below are the form forms and verification messages I would create.
buildForm(): void { this.heroForm = this.fb.group({ 'name': [this.hero.name, [ Validators.required, Validators.minLength(4), Validators.maxLength(24), forbiddenNameValidator(/bob/i) ] ], 'address': this.fb.group({ 'city': [''], 'state': [''] }), 'alterEgo': [this.hero.alterEgo], 'power': [this.hero.power, Validators.required] }); this.heroForm.valueChanges .subscribe(data => this.onValueChanged(data)); this.onValueChanged();
Expected formErrors and validationMessages
formErrors = { 'name': '', 'power': '', 'address': { 'state': '', 'city': '' } }; validationMessages = { 'name': { 'required': 'Name is required.', 'minlength': 'Name must be at least 4 characters long.', 'maxlength': 'Name cannot be more than 24 characters long.', 'forbiddenName': 'Someone named "Bob" cannot be a hero.' }, 'power': { 'required': 'Power is required.' }, 'address': { 'city': { 'required': 'City is required.', 'minlength': 'City must be at least 4 characters long.', }, 'state': { 'required': 'State is required.', 'minlength': 'State must be at least 4 characters long.', } } };
Below is onValueChanged
onValueChanged(data?: any) { if (!this.heroForm) { return; } const form = this.heroForm; for (const field in this.formErrors) { // clear previous error message (if any) this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; for (const key in control.errors) { this.formErrors[field] += messages[key] + ' '; } } } }
How to update the above onValueChanged function to support checking for nested group groups?
I do this above because I have a wizard form and I want to check the group of nested forms before proceeding to the next step of the wizard. Each step of the wizard contains a group of nested forms. The current step of the wizard must be valid before moving on to the next. I do not want to put the contents of the wizard in several components, because all the data must be from the wizard must be sent together at the end to a remote service. Therefore, I do not see the value complicated, having several components.