Angular - All Input values are changing on select changes in formarray

Viewed 450

I'm working with angular material, but I have a problem in Angular 7 with a FormArray.

When I only have 1 item, it's working fine, but once I add another item dynamically, selects has correct value, but the input related has the same value which is wrong. Example:

1) change select 1:

  • Value of select 1: Item1 (correct)
  • Value of input 1: Code1 (correct)

2) Add a new item, copying previous values:

  • Value of select 1: Item1 (correct)
  • Value of input 1: Code1 (correct)
  • Value of select 2: Item1 (correct)
  • Value of input 2: Code1 (correct)

3) Change select 2 to Item2:

  • Value of select 1: Item1 (correct)
  • Value of input 1: Code2 (incorrect)
  • Value of select 2: Item2 (correct)
  • Value of input 2: Code2 (correct)

The input 1 should have "Code1" as value, but all inputs changes its values to the last changed select.

Here is my code:

Template:

<div formArrayName="transporteArrayItems">
        <div *ngFor="let item of transporteForms.controls; let i=index" [formGroupName]="i">

          <div class="form-group row">
            <div class="col-md-9 dropdown-input-inline">
              <mat-form-field appearance="outline">
                <mat-label>Condiciones de entrega</mat-label>
                <mat-select placeholder="Condiciones de entrega" formControlName="selectCondicionesEntrega"
                  (selectionChange)="condicionesEntregaChange($event, i)" required>
                  <mat-option *ngFor="let condicion of listCondiciones" [value]="condicion">
                    {{condicion.descripcion}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
            <div class="col-md-3">
              <mat-form-field appearance="outline">
                <mat-label>Código</mat-label>
                <input formControlName="condicionesCodigo"
                  [value]="item.controls.selectCondicionesEntrega.value.codigo || null" matInput required disabled>
              </mat-form-field>
            </div>
          </div>
        </div>
      </div>

ts:

 addTransporteItem(index) {


    const transporteItem = this.formBuilder.group({
      selectCondicionesEntrega: ['', Validators.required],
      condicionesCodigo: ['', Validators.required]
    });

    let formularioAnterior = transporteItem;

    if (index != undefined) {

      Object.assign(formularioAnterior, this.transporteForm.controls.transporteArrayItems['controls'][index]);
      this.transporteForms.push(formularioAnterior);
    } else {
      this.transporteForms.push(transporteItem);
    }
  }

I'm not sure if could be because I'm copying the previous formgroup, but tried different ways and still didn't work.

Working example: https://codesandbox.io/s/determined-satoshi-xpkpf

Thanks in advance.

0 Answers
Related