Catherine S.
Catherine S.

Reputation: 229

Validators for reactive form not passing from parent form component to child component

I have a parent form component that is using a child form component. I am using Angular reactive forms. I have no issues setting the values in the child form component, but the validators are no longer working. In the parent form, I have instantiated the form group similar to the following:

this.editUserForm = this.fb.group ({
  phone: ['123-456-1234'],
  fax: [null],
  email: [null],
  website: [null],
  editUserForm_Address : this.fb.group ({
    address1: ['123 Elm Street', Validators.required],
    address2: [null],
    city: ['Dummy City', Validators.required],
    state: ['Dummy State', Validators.required],
    zipcode: ['11111', Validators.required],
    country: ['USA', Validators.required]
  })
});

The parent component html uses the child component:

<form [formGroup] = "editUserForm">
<address-form formGroupName = "editUserForm_Address"></address-form>
</form>

The child component class is like:

export class AddressFormComponent implements OnInit {

  public addressFormGroup: FormGroup;

  @Input()

  constructor(private controlContainer: ControlContainer) { }

  ngOnInit() {
    this.addressFormGroup = <FormGroup>this.controlContainer.control;
  }

}

The child component html is like this (just Address 1 for an example):

   <ng-container [formGroup] = "addressFormGroup">   
    <div class = "row">
     <div class = "form-group col-12" [ngClass]="{'error': (addressFormGroup.controls['address1'].errors)">
       <label for="street" >Address 1*</label>
       <input placeholder = "Address 1" class="form-control" formControlName="address1">
       <div *ngIf="(addressFormGroup.controls['address1'].errors)" class="error-msg">
        <div [hidden]="!addressFormGroup.controls['address1'].errors.required"
 class = "input_feedback">Address 1 is required.</div>
       </div>
     </div>

I have no issues with the values showing up, like "123 Elm Street" for the address1. However, the Validators no longer work like they used to when everything was just in the parent form. I've also tried setting validators using the setValidators() method, but that was not successful.

Upvotes: 0

Views: 1948

Answers (1)

Bruno
Bruno

Reputation: 316

I'm not sure what the exact problem is, but I was able to recreate your form on StackBlitz and validation works as expected.

What I did was just pass editUserForm_Address formGroup to child component.

Here is working StackBlitz -> https://stackblitz.com/edit/angular-pbfuut

<form [formGroup] = "editUserForm">
  <address-form [formGroup]="editUserForm.get('editUserForm_Address')"></address-form>
</form>

The key is passing the actual formGroup to child component -> [formGroup]="editUserForm.get('editUserForm_Address')"

Upvotes: 2

Related Questions