Angular Auto Bulk Validation of Active Form According to Controls

I'm not sure if this is the intended behavior; 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>
      

Run codeHide result


When I submit the form and console.log(this.formGroup)

, the object errors

name

AbstractControl

is null. I expected it to have Object

with required: true

. Where am I going wrong?

+3


source to share


1 answer


Thanks to @yurzui for pointing out the related issue - this is a workaround that will just check 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 };
};
      

Run codeHide result




This must be explicitly included as a validator, of course:

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

Run codeHide result


+1


source







All Articles