2016-11-06 82 views
0

嘗試計算總計payOffs.amount(payOffs是FormArray)。不知道如何正確地做到這一點,所以總數會觀察對當前和新數量的更改。這裏是我花了作爲基礎代碼plnkr:http://plnkr.co/edit/nHSIsciSZNTQzQjxkXsk?p=previewangular2動態表單計算金額總計

<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); 
    } 
} 

回答

1

或者你可以觀察整個表格陣列上的變化,通過訂閱在構造函數中的變化。

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)); 
}); 
+0

我將@ danny的console.log()添加到我的plunker中:http://plnkr.co/edit/Q5HYcpnPQosSYvk2KkoP?p =預覽 – Andriy

+0

令人驚歎!謝謝,它的工作原理!另一個問題:我怎樣才能在表單中以相同的方式顯示? – Alla

+0

@你可以將減少的結果保存到組件的屬性中並將其顯示在窗體上。用plunkr檢查Andriy的解決方案,它在表格中顯示總數。 –

0

我添加了一個功能:

// calculate a sum of all payoffs 
sumPayOffs() { 
    return this.myModel.payOffs.reduce((sum, val) => sum + val.amount, 0); 
} 

和HTML(之前 「添加還清」按鈕)我添加了只讀號碼字段,顯示總和:

<td> 
    <input type="number" step="0.01" class="sum" readonly size=6 [value]="sumPayOffs()"> 
</td> 
<td colspan="3" style="text-align: center; padding: .5em;"> 
    <button (click)="addPayOff($event)" 
      style="color: white; background: rgba(0, 150, 0, 1)">Add Pay Off</button> 
</td> 

我更改了付款現金類型從文本號碼,因此插入模式值將是數字。

更新plunker:http://plnkr.co/edit/Q5HYcpnPQosSYvk2KkoP?p=preview

+0

謝謝@Andriy! – Alla

+0

我也試圖將總體納入模型和表單控件。模型工作正常,但控制不顯示值..任何想法? – Alla

+0

請更新您的或我的plunker(應該顯示兩個提到的值)並指出我遇到的問題,我將盡力幫助 – Andriy