[Formarray] [SubmitForm] [Angular] Невозможно передать значение из formarray - PullRequest
0 голосов
/ 19 марта 2020

Я пытаюсь представить значение, поступающее с formarray. Однако это не работает ... Вот код

<form  *ngIf="incomeForm" [formGroup]="incomeForm" (ngSubmit)="onSubmitForm()">
  <table class="table table-border">
    <thead>
    <th>Description</th>
    <th>somme</th>
    </thead>
    <tbody>
    <ng-container formArrayName="budgetIncomes" *ngFor="let item of incomesArray.controls; let i=index">

        <tr *ngIf="item.get('isEditable').value" [formGroupName]="i">

          <td><input type="text" ngModel  formControlName="label"></td>
          <td><input type="number" ngModel  formControlName="somme"
                     [ngStyle]="{'color': item.get('somme').value >=0? 'green' : 'red'}"></td>
          <button (click)="doneRow(item)">done</button>
        </tr>

        <tr *ngIf="!item.get('isEditable').value">
            <td>{{item.get('label').value}}</td>
            <td>{{item.get('somme').value}}</td>
            <button (click)="editRow(item)">edit</button>
        </tr>
    </ng-container>
    </tbody>
  </table>
  <div class="action-container">
    <button class="add" (click)="addIncome()">Add Income</button>
  </div>
  <button type="submit" class="btn btn-primary">Enregistrer</button>
</form>

<p class="result" [ngStyle]="{'color': getSum()>=0? 'green' : 'red'}">{{getSum()}}</p>
  onSubmitForm() {
  const formValue = this.incomeForm.value;
  const newBudget = new Budget(
formValue['label'],
formValue['somme']
 )
 this.budgetService.validateBudget(newBudget);

}

Кажется, значение из newBudget не определено, но я не понимаю, почему?

Есть идеи?

Спасибо заранее! :)

1 Ответ

0 голосов
/ 19 марта 2020

Ваша структура формы выглядит примерно так:

-- FormGroup: incomeForm
---- FormArray: budgetIncomes
------ FormGroup: 
-------- FormControl: label
-------- FormControl: somme

Это означает, что структура данных значения вашей формы будет выглядеть следующим образом:

{
  incomeForm: {
    budgetIncomes: [
      { 
        label: string,
        somme: number
      },
      { 
        label: string,
        somme: number
      },
      // ... 
    ]
  }
}

Таким образом, вы сможете получить массив Budget объектов со следующим кодом:

onSubmitForm() {
  const formValue = this.incomeForm.value;
  const budgets = formValue.budgetIncomes.map(group => new Budget(
    group['label'],
    group['somme']
  ));

  // TODO: validate budgets...
}
...