I'm getting an error: formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance
formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance
. I'm not sure what am I doing wrong. I would like the FormGroup to iterate several time(using ngFor
), and thought using formArrayName
would be the answer.
HTML:
<div formArrayName = "PaymentArray" *ngFor = "let meshalem of paymentForm.get('PaymentArray').controls;let i =index;"> <div [formGroup]="i"> <div class="row box-border" > <div class="form-group col-xs-12 col-sm-12 col-md-5 pull-right required"> <label class="control-label">מספר ת.ז. משלם</label> <input #PidField name="id_pay" id="id_pay" formControlName="id_pay" class="form-control input-lg" maxlength="9" (input)="searchChange($event.target.value)" /> </div> </div> </div> </div>
.ts File:
paymentForm = this.fb.group({ PaymentArray: this.fb.array([]) }) getPaymentList() { this._adminService.getPayment(this.id).subscribe(res => { if(res.isSuccess) { this.PaymentList = res.data ; this.PaymentList.forEach((pays) => { this.meshalemArray = this.paymentForm.get('PaymentArray') as FormArray; this.meshalemArray.push(this.fb.group({ id_pay:[pays.id_pay,Validators.compose([Validators.pattern("^[0-9]*$"), Validators.required])], numberRooms:[pays.numberRooms], sum: [pays.sum], paymentMethod:[pays.paymentMethod], credit:[pays.credit], })) }) } else { //TODO } }) }
Error is causing because you are not using FormArray
inside FormGroup
. Just wrap the FormArray
inside the FormGroup
:-
<form [formGroup]="paymentForm">
<div formArrayName = "PaymentArray" *ngFor = "let meshalem of paymentForm.get('PaymentArray').controls;let i =index;">
<div [formGroup]="i">
<div class="row box-border" >
<div class="form-group col-xs-12 col-sm-12 col-md-5 pull-right required">
<label class="control-label">מספר ת.ז. משלם</label>
<input #PidField name="id_pay" id="id_pay" formControlName="id_pay" class="form-control input-lg"
maxlength="9" (input)="searchChange($event.target.value)" />
</div>
</div>
</div>
</div>
</form>
And I think <div [formGroup]="i">
should be eigther <div [formGroupName]="i">
or <div [formGroup]="meshalem">
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.