import { Component, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { FormArray, FormBuilder, FormGroup } from '@angular/forms'; import { distinctUntilChanged } from 'rxjs/operators'; import { ReceivePaymentDatasource } from './receive-payment-datasource'; import { PrintType } from '../bills/bill'; @Component({ selector: 'app-receive-payment', templateUrl: './receive-payment.component.html', styleUrls: ['./receive-payment.component.css'] }) export class ReceivePaymentComponent { choices = { REGULAR_BILL: [ { id: 2, name: 'Cash', amount: 0 }, { id: 3, name: 'Credit Card', amount: 0 }, { id: 5, name: 'Bill To Company', amount: 0 }, { id: 6, name: 'Tip', amount: 0 } ] , NO_CHARGE: [ { id: 4, name: 'No Charge', amount: 0 } ], STAFF: [ { id: 10, name: 'Staff Account', amount: 0 } ] }; type: PrintType; amount: number; balance: number; form: FormGroup; dataSource: ReceivePaymentDatasource; displayedColumns = ['name', 'amount']; constructor( public dialogRef: MatDialogRef, private fb: FormBuilder, @Inject(MAT_DIALOG_DATA) public data: {type: PrintType, amount: number} ) { this.createForm(); this.type = data.type; this.amount = data.amount; this.balance = data.amount; this.form.setControl('amounts', this.fb.array( this.choices[this.type].map( x => this.fb.group({ name: [x.name], amount: [''] }) ) )); this.dataSource = new ReceivePaymentDatasource(this.choices[this.type]); this.listenToAmountChange(); } createForm() { this.form = this.fb.group({ amounts: '' }); } listenToAmountChange() { const array = this.form.get('amounts') as FormArray; this.choices[this.type].forEach( (z, i) => array.controls[i].valueChanges.pipe( distinctUntilChanged() ).subscribe(x => { this.choices[this.type].find(s => s.name === x.name).amount = (x.amount === '' ? 0 : parseInt(x.amount, 10)); this.balance = this.amount - this.choices[this.type].reduce((a, c) => a + c.amount, 0); }) ); } accept(): void { this.dialogRef.close(this.choices[this.type]); } }