Search code examples
javascriptangulartypescriptformsformarray

Form array not saving input


I have this form array:

this.chavesNfeForm = new FormArray([
        new FormGroup({
          chave: new FormControl(""),
        })
      ]);

And I use on my aplication like this:

 <form [formGroup]="chavesNfeForm" *ngIf="this.nfReferenciadaForm.value.referenciada==1" >
      <ng-container *ngFor="let chaves of chavesNfeForm.controls; let i = index">
        <div class="row">
          <div class="col-8">
            <mat-form-field>
              <mat-label><i class="fas fa-key"></i> Chave NF-e </mat-label>
              <input matInput required formcontrolName="chave">
            </mat-form-field>
          </div>
        </div>
      </ng-container>
    </form>

So that I can have mutiple and dinamic forms as needed, having the user being able to add or remove as much as he needs.

However, when I try to output the value of the form for later use I get nothing, not a single value is stored on the form.

I have no idea what I am doing wrong here. (Currently using Angular 8 and Typescript)


Solution

  • Try using formControl instead of formcontrolName

    // With form control
    <form
      [formGroup]="chavesNfeForm"
      *ngIf="this.nfReferenciadaForm.value.referenciada == 1"
    >
      <ng-container *ngFor="let chaves of chavesNfeForm.controls; let i = index">
          <div class="row">
            <div class="col-8">
              <mat-form-field>
                <mat-label><i class="fas fa-key"></i> Chave NF-e </mat-label>
                <input matInput required [formControl]="chaves.get('chave')" />
              </mat-form-field>
            </div>
        </div>
      </ng-container>
    </form>