3
votes

I'm not sure if this is the intended behaviour; I have the following:

this.formGroup = this.fb.group({
  name: this.fb.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required]
  })
});
<div formGroupName="name">
  <input type="text" formControlName="firstName">
  <input type="text" formControlName="lastName">
</div>

When I submit the form and console.log(this.formGroup), the errors object of the name AbstractControl is null. I expected it should have an Object with required: true. Where am I going wrong?

1
If the field is valid, then errors is null. This is just how it is :) - AJT82
But both child fields are empty! - Sammy
Ah okay, you didn't mention that ;) - AJT82
Where do you use formGroup in your template? - yurzui
github.com/angular/angular/issues/10530 Here is plunker plnkr.co/edit/B6vm3m6CZ170kijAOQaF?p=preview As we can see the errors are not bubbling - yurzui

1 Answers

1
votes

Thanks to @yurzui for pointing out the related issue -- this is a workaround that will simply check for both controls:

import {AbstractControl} from '@angular/forms';

export const nameValidator = (control: AbstractControl): {[key: string]: boolean} => {
	const firstName = control.get('firstName');
	const lastName = control.get('lastName');
	if (!firstName || !lastName) {
		return null;
	}
	return firstName.value && lastName.value ? null : { required: true };
};

This needs to be explicitly included as a validator of course:

name: this.fb.group({
  firstName: ['', Validators.required],
  lastName: ['', Validators.required]
}, {validator: nameValidator}),