本文介绍了angular2动态形式计算数量总计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试计算总的payOffs.amount(payOffs是一个FormArray).不确定如何正确执行操作,因此总计将观察到金额的当前值和新值的变化.这是我作为基本代码使用的plnkr: http://plnkr.co/edit/nHSIsciSZNTQzQjxkXsk?p =预览

Trying to calculate a total payOffs.amount (payOffs is a FormArray). Not sure how to do it properly so the total would observe changes to current and new for amounts. Here is a plnkr that I took as a base code: http://plnkr.co/edit/nHSIsciSZNTQzQjxkXsk?p=preview

  <form (ngSubmit)="onSubmit()" [formGroup]="form">

<label>Name</label>
<input type="text" formControlName="name" [(ngModel)]="myModel.name" placeholder="Name">

<p>Pay Offs</p>
<table class="simple-table">
  <tr>
    <th>Amount</th>
    <th>Date</th>
    <th>Final?</th>
    <th></th>
  </tr>
<tbody>
  <tr *ngFor="let po of form.find('payOffs').controls; let i = index">
    <td>
      <input type="text" size=10 [formControl]="po.controls.amount" [(ngModel)]="myModel.payOffs[i].amount">
    </td>
    <td>
      <input type="text" [formControl]="po.controls.date" [(ngModel)]="myModel.payOffs[i].date">
    </td>
    <td>
      <input type="checkbox" [formControl]="po.controls.final" [(ngModel)]="myModel.payOffs[i].final">
    </td>
    <td>
      <button (click)="deletePayOff(i)" style="color: white; background: rgba(255, 0, 0, .5)">x</button>
    </td>
  </tr>
</tbody>
<tr>
  <td colspan="4" style="text-align: center; padding: .5em;">
    <button (click)="addPayOff($event)" style="color: white; background: rgba(0, 150, 0, 1)">Add Pay Off</button>
  </td>
</tr>
</table>
@Component({
  selector: 'my-app',
  templateUrl: 'app/app.html',
  directives: [REACTIVE_FORM_DIRECTIVES],
  providers:  []
})
export class AppComponent {
  form: FormGroup;
  myModel:any;

  constructor() {
    // initializing a model for the form to keep in sync with. 
    // usually you'd grab this from a backend API
    this.myModel = {
      name: "Joanna Jedrzejczyk",
      payOffs: [
        {amount: 111.11, date: "Jan 1, 2016", final: false},
        {amount: 222.22, date: "Jan 2, 2016", final: true}
        ]
    }

    // initialize form with empty FormArray for payOffs
    this.form = new FormGroup({
      name: new FormControl(''),
      payOffs: new FormArray([])
    });

    // now we manually use the model and push a FormGroup into the form's FormArray for each PayOff
    this.myModel.payOffs.forEach( 
      (po) => 
        this.form.controls.payOffs.push(this.createPayOffFormGroup(po))
    );
  }

  createPayOffFormGroup(payOffObj) {
    console.log("payOffObj", payOffObj);
    return new FormGroup({
      amount: new FormControl(payOffObj.amount),
      date: new FormControl(payOffObj.date),
      final: new FormControl(payOffObj.final)
    });
  }

  addPayOff(event) {
    event.preventDefault(); // ensure this button doesn't try to submit the form
    var emptyPayOff = {amount: null, date: null, final: false};

    // add pay off to both the model and to form controls because I don't think Angular has any way to do this automagically yet
    this.myModel.payOffs.push(emptyPayOff);
    this.form.controls.payOffs.push(this.createPayOffFormGroup(emptyPayOff));
    console.log("Added New Pay Off", this.form.controls.payOffs)
  }

  deletePayOff(index:number) {
    // delete payoff from both the model and the FormArray
    this.myModel.payOffs.splice(index, 1);
    this.form.controls.payOffs.removeAt(index);
  }
}

推荐答案

或者您可以通过订阅构造函数中的更改来观察整个表单数组的更改.

Or you could observe changes on the whole form array, by subscribing to the changes in the constructor.

this.form.controls.payOffs.valueChanges.subscribe((change) => {
  const calculateAmount = (payoffs: any[]): number => {
    return payoffs.reduce((acc, current) => {
       // also handling case when a new pay off is added with amount of null
       return acc + parseFloat(current.amount || 0);
    }, 0);
  }

  console.log(calculateAmount(this.form.controls.payOffs.value));
});

这篇关于angular2动态形式计算数量总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 16:54