Angular Input value is not changing in FormArray

55 Views Asked by At

I have a FormArray in PreprocesssingForm. Here, Sequence No is not getting changed when I add a new row.

<tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticItems['controls']; let i = index" [formGroupName]="i">
    <td> {{ i+1 }} </td>

    <td class="mat-cell">
    <mat-form-field appearance="outline" style="width: 4rem;text-align: center;">
        <input matInput formControlName="operational_sequence_no" type="text" value = {{ i+1 }} readonly>
    </mat-form-field>
    </td>

<td> {{ i+1 }} </td> is showing correctly 1 2 3 4 5.
I tried value = {{i+1}}, [value] = "i+1", value = "{{i+1}}".
But, It is showing 1 1 1 1 1.

[ngModel] = "i+1" is working, but console is telling that it is depreceated.

1

There are 1 best solutions below

0
On

if you use FormControl not use "value". You should give value to the FormControl

I imagine you have a getter(*)

get arithmeticItems()
{
   return PreprocessingForm.controls.arithmeticItems as FromArray
}

And a function that return a formGroup

newArithmeticItem()
{
   return new FormGroup({
     operational_sequence_no:new FormControl(0)
     ...
   })
}

When add an element

addArithmeticItem()
{
    this.arithmeticItems.push(this.newArithmeticItem())
}

The only is change your newArithmeticItem like:

newArithmeticItem()
{
   return new FormGroup({
     //see how you give value when you create the formControl
     operational_sequence_no:new FormControl(this.arithmeticItems.controls.length+1) 
     ...
   })
}

But... be careful, if you remove an item you should "recalculate" the "operational_sequence"

removeArithmeticItem(index:number)
{
    this.arithmeticItems.removeAt(index)
    //renum operational_sequence
    //I renum all instead of only from index to last one
    //If you have not a laaaaaarge quantity it's OK
    this.aritmeticItems.controls.forEach((x:AbstractControl,i:number)=>{
       x.patchValue("operational_sequence_no",i+1)
    })
}

(*)I know you have not, but it's good to have a getter of the formArrays