响应式表单的验证程序未从父表单组件传递到子组件

时间:2019-03-04 22:22:51

标签: angular angular-reactive-forms

我有一个使用子窗体组件的父窗体组件。我正在使用Angular反应形式。在子窗体组件中设置值没有问题,但是验证器不再起作用。在父表单中,我实例化了类似于以下内容的表单组:

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]
  })
});

父组件html使用子组件:

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

子组件类如下:

export class AddressFormComponent implements OnInit {

  public addressFormGroup: FormGroup;

  @Input()

  constructor(private controlContainer: ControlContainer) { }

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

}

子组件html如下(示例仅以地址1为例):

   <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>

我对显示的值没有问题,例如address1的“ 123 Elm Street”。但是,当所有内容都仅在父表单中时,验证器不再像以前那样工作。我也尝试过使用setValidators()方法设置验证器,但这并不成功。

1 个答案:

答案 0 :(得分:1)

我不确定确切的问题是什么,但是我能够在StackBlitz上重新创建您的表单,并且验证按预期进行。

我所做的只是将editUserForm_Address formGroup传递给子组件。

这里正在工作StackBlitz-> https://stackblitz.com/edit/angular-pbfuut

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

关键是将实际的formGroup传递给子组件-> [formGroup]="editUserForm.get('editUserForm_Address')"