【问题标题】:[Formarray][SubmitForm][Angular]Not able to submit value from formarray[Formarray][SubmitForm][Angular]无法从formarray提交值
【发布时间】:2020-06-30 18:59:20
【问题描述】:

我正在尝试提交来自表单数组的值。但是它不起作用......这是代码

<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 的值似乎是未定义的,但我不明白为什么?

有什么想法吗?

提前谢谢! :)

【问题讨论】:

  • 您能展示一下您是如何构建表单的吗

标签: angular submit formarray


【解决方案1】:

你的表单结构是这样的:

-- 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...
}

【讨论】:

  • 非常感谢您的回答。它的工作原理帮助我更好地理解它是如何工作的:)
  • 我还有一个问题。我无法在我的结果预算 hmtl 中正确显示结果,我不明白为什么 ^^; :stackblitz.com/github/LucNamur86/budget4
  • 我不确定你想实现什么,但如果我想看看实际模型是什么,我总是喜欢打印出顶层对象:stackblitz.com/edit/github-zwikzk
  • 谢谢。好吧,我正在尝试了解它是如何工作的,以及角度现在是如何工作的,哈哈。我想要的是在这个结果 html 部分中显示我的标签的值和我的 somme 以供以后使用:) 非常感谢,它真的对我有帮助!
猜你喜欢
  • 2020-08-29
  • 2018-08-10
  • 2019-01-31
  • 2018-01-29
  • 2019-02-10
  • 2021-09-16
  • 2017-11-16
  • 2018-08-14
  • 2019-08-13
相关资源
最近更新 更多