Home > database >  formarray adding row same value angular
formarray adding row same value angular

Time:06-27

Once I added a row to FormArray, why it has a same object displayed.

enter image description here

.HTML

<form [formGroup]="Form">
<div formArrayName="ItemRec">
<table>
<thead>
<tr>
<th>FORM</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let ItemRec of ItemRec.controls; let i = index;" 
[formGroupName]="i">
<td (click)="removeRow(i)" style="width:100px" align="center">
<i ></i></td>
<td>
<input style="width:200px" 
formControlName="dr" ngModel={{transactionCode}}>
</td>
</tr>
</tbody>
</table>
</form>

.TS

this.Form = this.fb.group({
    Id:['0'],
    ItemRec: this.fb.array([this.CreateItemRec()])
  })
 }  


  CreateItemRec(): FormGroup {
    return this.fb.group({
      id:[0],
      dr: new FormControl('',Validators.required),
    })
}

 get ItemRec(): FormArray {
  return <FormArray>this.Form.get('ItemRec') as 
  FormArray
 }


addRow(): void {
  this.ItemRec?.push(this.CreateItemRec());

CodePudding user response:

Try the following:

<tr *ngFor="let ItemRec of ItemRec.controls; let i = index">
  <td (click)="removeRow(i)" style="width: 100px" align="center">
    <i ></i>
  </td>
  <td>
    <input
      style="width: 200px"
      
      [formGroupName]="i"
    />
  </td>
</tr>

I simply removed the ngModel={{transactionCode}} and moved the [formGroupName]="i" to the input

Reference: https://angular.io/guide/reactive-forms#creating-dynamic-forms

CodePudding user response:

You has a FormArray of FormGroup -really if only has one property you should use a FormArray of FormControl, see, e.g. this SO, or this great entry blog to understand the diference-

As always you use a FormArray, you should use a "getter"

get ItemRec()
{
   return this.myForm.get('formArray') as FormArray
}

And if you have a FormArray of formGroup you can use a function that return a formGroup

createFormGroup(data:any=null)
{
   data=data || {dr:null,other_property:null,...}
   return new FormGroup({
       dr:new FormControl(data.dr),
       other_property:new FormControl(data.other_property),
       ...
   })
}

Now you can use a function

add()
{
   //get the value
   const value=this.ItemRec.at(this.itemRec.controls.length-1).value;
   //simply push a new FormGroup
   this.ItemRec.push(this.createFormGroup(value)
}

If you use a FormArray of FormGroup is unnecesary to have a function that return the formGroup, you can simply

add()
{
   //get the value
   const value=this.ItemRec.at(this.itemRec.controls.length-1).value;
   //simply push a new FormGroup
   this.ItemRec.push(new FormControl(value))
}

NOTE: never use in the same tag formGroupName and ngModel. One is about ReactiveForms and another one about Template driven Form

NOTE2: the variable in your loop should be different that the FormArray, e.g.

<!--the variable to iterate should be different
    than the FormArray-->
<tr *ngFor="let group of ItemRec.controls;....>
  • Related