简体   繁体   中英

Using a control of parent formgroup inside nested formgroupname

I am creating a form where I am using formgroupname inside a formgroup.

Html:

<form [formGroup]="parentForm">
  <div formGroupName="childGroup">
    <input type="text" formControlName="childControl1">
    <input type="text" formControlName="parentControl1">
    <input type="text" formControlName="childControl2">
  </div>
</form>

Ts Code

this.parentForm = this.formBuilder.group({
  parentControl1: new FormControl(),
  childGroup: this.formBuilder.group({
  childControl1: new FormControl(),
  childControl2: new FormControl(),
 })
})

I am getting following error.

Error : Cannot find control with path: 'childGroup -> parentControl1'

Note: I can't change html structure. Need a workaround of can I achieve this

"parentControl" not belong to ChildGroup

  1. A workAround is use a getter

    get parentControl1():FormControl { return this.parentForm.get('parentControl1') as FormControl }

    And use [formControl]

     <div formGroupName="childGroup"> <input type="text" formControlName="childControl1"> <input type="text" [formControl]="parentControl1"> <input type="text" formControlName="childControl2"> </div>
  2. Another workaround is use some like

    <div formGroupName="childGroup"> <input type="text" formControlName="childControl1"> <input type="text" [ngModel]="this.parentForm.get('parentControl1').value" (ngModelChange)="this.parentForm.get('parentControl1').setValue($event)" [ngModelOptions]="{standalone:true}"> <input type="text" formControlName="childControl2"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM