I need to add currency
pipe to my total
column, but the problem is that it is an input
field, How do I do that?
<div id="forms" class="page-layout simple fullwidth" fxLayout="column">
<button routerLink='/searchLoan' mat-raised-button fxFlex="4" class="btn-style-1" style="align-self: flex-end;margin-right: 30px;margin-top: 15px;">View
List</button>
<div class="content p-24">
<div class="mb-24" fxLayout="column" fxLayoutAlign="start" fxLayout.gt-md="row">
<mat-card>
<mat-card-title style='margin-top: -15px;'>New Loan</mat-card-title>
<mat-card-content>
<form class="p-24 mr-24" fxLayout="column" fxLayoutAlign="start" fxFlex="1 0 auto" name="form" [formGroup]="newLoanForm">
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<mat-form-field appearance="outline" fxFlex="100%" class="pr-4">
<mat-label>Customer </mat-label>
<mat-select required formControlName='customerId'>
<mat-option *ngFor='let customer of customerList' [value]="customer.customerId">
{{customer.name}}
</mat-option>
</mat-select>
<mat-icon matSuffix>face</mat-icon>
</mat-form-field>
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<button type="button" mat-stroked-button class='addCustomerButton' (click)="openCustomerDialog()" fxFlex='100'>Add
<mat-icon matSuffix>add_box</mat-icon>
</button>
</div>
</div>
<div fxLayout="row" fxLayoutAlign="start center" fxFlex>
<mat-form-field appearance="outline" fxFlex="row" fxFlex="50%" class="pr-4">
<mat-label>Referring Organization</mat-label>
<mat-select required formControlName="orginizationId">
<mat-option *ngFor='let organization of organizationList' [value]="organization.orginizationId">
{{organization.orginizationName}}
</mat-option>
</mat-select>
<mat-icon matSuffix class="secondary-text">work_outline</mat-icon>
<mat-error> Referring Organization is required!</mat-error>
</mat-form-field>
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<button type="button" mat-stroked-button class='addCustomerButton' (click)="openOrganizationDialog()" fxFlex='100'>Add
<mat-icon matSuffix>add_box</mat-icon>
</button>
</div>
<mat-form-field appearance="outline" fxFlex="row" fxFlex="50%" class="pr-4">
<mat-label>Sales Person</mat-label>
<mat-select required formControlName="salesPersonId">
<mat-option *ngFor="let person of salesPersonList" [value]="person.salesPersonId">
{{person.name}}
</mat-option>
</mat-select>
<mat-icon matSuffix class="secondary-text">supervised_user_circle</mat-icon>
<mat-error> Sales Person is required!</mat-error>
</mat-form-field>
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<button type="button" mat-stroked-button class='addCustomerButton' (click)="openSalesPersonDialog()" fxFlex='100'>Add
<mat-icon matSuffix>add_box</mat-icon>
</button>
</div>
</div>
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<mat-form-field appearance="outline" fxFlex="row" fxFlex="50%" class="pr-4">
<mat-label>Invoice Number</mat-label>
<input type='number' formControlName="invoiceNumber" matInput name="" id="" placeholder="Invoice Number" required>
<mat-icon matSuffix>receipt</mat-icon>
</mat-form-field>
<mat-form-field appearance="outline" fxFlex="row" fxFlex="50%" class="pr-4">
<mat-label>Invoice Date</mat-label>
<!-- <input type='date' matInput name="" id="" formControlName="invoiceDate" placeholder="Invoice Date" required> -->
<input matInput [(ngModel)]="loanDate" ngModel [ngModelOptions]="{standalone: true}" [matDatepicker]="picker" placeholder="Choose a date" required>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<!-- <mat-icon matSuffix>date_range</mat-icon> -->
</mat-form-field>
</div>
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<mat-form-field appearance="outline" fxFlex="100" class="pr-4">
<mat-label>Notes</mat-label>
<textarea matInput name="" id="" formControlName="notes" placeholder="Notes" required></textarea>
<mat-icon matSuffix>assignment</mat-icon>
</mat-form-field>
</div>
<form [formGroup]="loanProductForm">
<table style="overflow-x: auto;display: inline-block; white-space: nowrap;">
<thead>
<tr class='tableHeader'>
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<td fxFlex="14" class="pr-4">Name</td>
<td fxFlex="14" class="pr-4">Price</td>
<td fxFlex="14" class="pr-4">Loan Term</td>
<td fxFlex="14" class="pr-4">Quantity</td>
<td fxFlex="14" class="pr-4">Deposit</td>
<td fxFlex="14" class="pr-4">Total</td>
<td fxFlex="14" class="pr-4">Action</td>
</div>
</tr>
</thead>
<tbody>
<tr formArrayName="products" *ngFor="let product of loanProductForm.get('products').controls; let i = index">
<div [formGroupName]="i" fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<td fxFlex="14">
<mat-form-field appearance="outline" fxFlex="100" class="pr-4">
<mat-label>Product </mat-label>
<mat-select formControlName="productId" (selectionChange)="onChangedProduct($event, i)" [id]="'productId' + i" required>
<mat-option *ngFor="let product of productList" [value]="product.productId">
{{product.name}}
</mat-option>
</mat-select>
</mat-form-field>
</td>
<td fxFlex="14">
<mat-form-field appearance="outline" fxFlex="100" class="pr-4">
<mat-label>Price </mat-label>
<input type='number' (keyup)="onPriceChange($event)" matInput formControlName="price" [id]="'price' + i" name="" placeholder="Price" required>
</mat-form-field>
</td>
<td fxFlex="14">
<mat-form-field appearance="outline" fxFlex="100" class="pr-4">
<mat-label>Loan Term </mat-label>
<mat-select formControlName="loanTermId" [id]="'loanTermId' + i" required>
<mat-option *ngFor="let loanTerm of loanTermList" [value]="loanTerm.loanTermId">
{{loanTerm.numberOfMonths}}
</mat-option>
</mat-select>
</mat-form-field>
</td>
<td fxFlex="14">
<mat-form-field appearance="outline" fxFlex="100" class="pr-4">
<mat-label>Quantity </mat-label>
<input type='number' formControlName="quantity" [id]="'quantity' + i" matInput name="" id="" placeholder="Quantity" required>
</mat-form-field>
</td>
<td fxFlex="14">
<mat-form-field appearance="outline" fxFlex="100" class="pr-4">
<mat-label>Deposit </mat-label>
<input type='number' formControlName="deposit" [id]="'deposit' + i" matInput name="" id="" placeholder="Deposit" required>
</mat-form-field>
</td>
<td fxFlex="14">
<div fxFlex="100" class="pr-4">
<!-- <mat-label>Total: </mat-label> -->
<input [disabled]="true" formControlName="total" [id]="'total' + i" matInput name="total" class='total' id="" placeholder="Total" style="color:black; font-weight:bold; width: unset;" required>
</div>
</td>
<td fxFlex="14">
<div fxFlex="100" class="pr-4">
<!-- <button class='deleteButton' mat-stroked-button style="color:red" > -->
<span class='deleteButton' (click)='deleteProduct(i)'><mat-icon >delete</mat-icon></span>
<!-- </button> -->
</div>
</td>
</div>
</tr>
<tr>
<td fxFlex="10">
<div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
<button type="button" mat-stroked-button class='addBtn btn-style-2' fxFlex='100' (click)='addProductButtonClick()'>Add
<mat-icon>add_box</mat-icon>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</form>
<button mat-raised-button fxFlex="15" [disabled]="dataSending" id='submitButton' class="btn-style-1" style="align-self: flex-end;margin-right: 30px;margin-top: 15px;" (click)="addNewLoan()">
<img *ngIf="dataSending" style="width : 24px"
src="../../../../../assets//images/spinner.gif" /> Save</button>
</form>
</mat-card-content>
</mat-card>
</div>
</div>
</div>
and here is my component
file code
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NewCustomerComponent } from '../../../../layout/components/customer/new-customer/new-customer.component';
import { NewOrganizationComponent } from '../../../../layout/components/organization/new-organization/new-organization.component';
import { AddSalesPersonComponent } from '../../../../layout/components/Sales/add-sales-person/add-sales-person.component'
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
import { CustomerService } from '../../../../services/customer/customer.service';
import { SalesPersonService } from 'app/services/sales person/sales-person.service';
import { OrganizationService } from 'app/services/organization/organization.service';
import { ProductService } from '../../../../services/product/product.service';
import { LoanTermService } from '../../../../services/loanTerms/loan-term.service'
import { LoanService } from '../../../../services/loan/loan.service';
import { LoanProductService } from '../../../../services/loanProducts/loan-product.service';
import * as _moment from 'moment'
import { Observable, pipe } from 'rxjs';
import { map, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import PNotify from 'pnotify/dist/es/PNotify';
@Component({
selector: 'app-new-loan',
templateUrl: './new-loan.component.html',
styleUrls: ['./new-loan.component.scss']
})
export class NewLoanComponent implements OnInit {
constructor(
private _formBuilder: FormBuilder,
private customerService: CustomerService,
private salesPersonService: SalesPersonService,
private organizationService: OrganizationService,
private productService: ProductService,
private loanTermService: LoanTermService,
private loanService: LoanService,
private loanProductService: LoanProductService,
private router: Router,
public dialog: MatDialog
) { }
loanDate;
dataSending = false;
installmentStartDate;
newLoanForm: FormGroup;
loanProductForm: FormGroup
customerList;
salesPersonList;
organizationList;
productList;
loanTermList;
totalValue = 0;
// price;
// quantity;
// deposit;
newRow = { productId: '', price: '', loanTermId: '', quantity: '', deposit: '', total: '' };
ngOnInit() {
this.newLoanForm = this._formBuilder.group({
customerId: ['', Validators.required],
orginizationId: ['', Validators.required],
salesPersonId: ['', Validators.required],
invoiceNumber: ['', Validators.required],
invoiceDate: ['', Validators.required],
notes: ['', Validators.required]
});
this.loanProductForm = this._formBuilder.group({
products: this._formBuilder.array([
this.addProductFormGroup()
])
});
this.loanProductForm.valueChanges.pipe(debounceTime(20)).subscribe((values) => {
(this.loanProductForm.get('products') as FormArray).controls.forEach(group => {
let total = (group.get('quantity').value * group.get('price').value) - group.get('deposit').value;
group.get('total').setValue(total);
});
});
this.getCustomers();
this.getSalesPersons();
this.getOrganizations();
this.getProducts();
this.getLoanTerms();
}
async getCustomers() {
this.customerList = await this.customerService.getCustomers().toPromise();
this.customerList.sort((a, b) => (a.customerId < b.customerId) ? 1 : -1);
}
async getSalesPersons() {
this.salesPersonList = await this.salesPersonService.getSalesPersons().toPromise();
this.salesPersonList.sort((a, b) => (a.salesPersonId < b.salesPersonId) ? 1 : -1);
}
async getOrganizations() {
this.organizationList = await this.organizationService.getOrganizations().toPromise();
this.organizationList.sort((a, b) => (a.orginizationId < b.orginizationId) ? 1 : -1);
}
getProducts() {
this.productService.getProducts().subscribe((response) => {
this.productList = response;
this.productList.sort((a, b) => (a.productId < b.productId) ? 1 : -1);
});
}
getLoanTerms() {
this.loanTermService.getLoanTerms().subscribe((response) => {
this.loanTermList = response;
});
}
addTableRow() {
this.newRow = { productId: '', price: '', loanTermId: '', quantity: '', deposit: '', total: '' };
// this.tableRows.push(this.newRow)
}
// isSame(prev, next) {
// return (prev.value === next.value)
// && (prev.quantity === next.quantity);
// }
addProductFormGroup(): FormGroup {
return this._formBuilder.group({
productId: ['', Validators.required],
price: [0, Validators.required],
loanTermId: ['', Validators.required],
quantity: [0, Validators.required],
deposit: [0, Validators.required],
total: [0, Validators.required],
});
}
addProductButtonClick(): void {
// let newGroup = this.addProductFormGroup();
// newGroup.markAsUntouched();
// (<FormArray>this.loanProductForm.get('products')).push(newGroup);
// const indexOfLastProduct = this.loanProductForm['controls']['products'].length - 1;
// this.loanProductForm['controls']['products']['controls'][indexOfLastProduct].markAsUntouched();
// console.log('Loan Products: ', this.loanProductForm.value)
(<FormArray>this.loanProductForm.get('products')).push(this.addProductFormGroup());
console.log('Loan Products: ', this.loanProductForm.value);
}
onPriceChange(e) {
//Nothing here, just for reference
}
onChangedProduct(event, index) {
const product =
this.productList.find(product => product.productId === event.value);
if (product) {
// console.log('Product is: ', product)
this.loanProductForm.get(['products', index + '', 'price']).patchValue(product.recomendedRetailPrice);
const loanTermId = null; // you need to find the loanTermId from loanTermList
this.loanProductForm.get(['products', index + '', 'loanTermId']).patchValue(product.loanTermId);
}
}
async addNewLoan() {
this.newLoanForm.value.invoiceDate = this.loanDate.format();
let loanProducts = this.loanProductForm.value.products;
this.newLoanForm.value.loanProducts = loanProducts;
let loanTerm;
// document.getElementById('submitButton').style.display = 'none';
this.dataSending = true;
// Calculating installment start Date
if (this.loanDate.date() <= 14) {
this.installmentStartDate = this.loanDate.add(1, 'M');
this.installmentStartDate = this.loanDate.date(10);
}
else {
this.installmentStartDate = this.loanDate.add(2, 'M');
this.installmentStartDate = this.loanDate.date(10);
}
// Adding installment start date to each product
loanProducts.forEach(product => {
product.installmentStartDate = this.installmentStartDate.format();
});
console.log('LoanProducts: ', loanProducts);
let productsProcessed = 0;
loanProducts.forEach(async product => {
await this.loanTermService.getLoanTerm(product.loanTermId).subscribe((response: any) => {
// console.log('Number of months: ', response.numberOfMonths)
loanTerm = response.numberOfMonths;
product.monthlyInstallment = product.total / loanTerm;
}, error => {
console.log('Error while retrieving loanTermId: ', error);
});
productsProcessed++;
if (productsProcessed === loanProducts.length) {
// Posting loan after the response of loanTerms Service
this.loanService.postLoan(this.newLoanForm.value).subscribe((response: any) => {
console.log('Loan added successfully: ', response);
PNotify.success({
title: 'Loan added Successfully',
text: 'Redirecting to list page',
minHeight: '75px'
});
// document.getElementById('submitButton').style.display = 'initial';
this.dataSending = false;
this.router.navigate(['searchLoan']);
}, (error) => {
console.log('Error occured while adding loan: ', error);
PNotify.error({
title: 'Error occured while adding loan',
text: 'Failed to add new loan',
minHeight: '75px'
});
// document.getElementById('submitButton').style.display = 'initial';
this.dataSending = false;
});
// Posting of loan ends here
}
});
this.newLoanForm.value.loanProducts = loanProducts;
console.log('Loan Products: ', this.loanProductForm.value);
}
deleteProduct(i) {
(this.loanProductForm.get('products') as FormArray).removeAt(i);
}
// Opening of dialogs
openCustomerDialog(): void {
const dialogRef = this.dialog.open(NewCustomerComponent, {
width: '700px',
height: '600px',
data: {
view: 'dialog'
}
});
dialogRef.afterClosed().subscribe(async result => {
console.log('OpenCustomer Dialog was closed');
await this.getCustomers().then(() => {
let customerPreSelectId = this.customerList[0].customerId;
this.newLoanForm.patchValue({
customerId: customerPreSelectId
})
});
});
}
openOrganizationDialog(): void {
const dialogRef = this.dialog.open(NewOrganizationComponent, {
width: '800px',
height: '600px',
data: {
view: 'dialog'
}
});
dialogRef.afterClosed().subscribe(async result => {
console.log('OpenOrganizations was closed');
await this.getOrganizations().then(() => {
let organizationPreSelectId = this.organizationList[0].orginizationId;
this.newLoanForm.patchValue({
orginizationId: organizationPreSelectId
});
});
});
}
openSalesPersonDialog(): void {
const dialogRef = this.dialog.open(AddSalesPersonComponent, {
width: '700px',
height: '600px',
data: {
view: 'dialog'
}
});
dialogRef.afterClosed().subscribe(async result => {
console.log('OpenSalesPerson dialog was closed');
await this.getSalesPersons().then(() => {
let salesPersonPreSelectId = this.salesPersonList[0].salesPersonId;
this.newLoanForm.patchValue({
salesPersonId: salesPersonPreSelectId
})
});
});
}
}
I already tried using a regular method, but it was not working. Picture for better understanding.
You can use [value] property to use your pipe
<td fxFlex="14">
<div fxFlex="100" class="pr-4">
<!-- <mat-label>Total: </mat-label> -->
<input [disabled]="true" [value]="loanProductForm.get('products').controls[i].value.total | yourPipe" formControlName="total" [id]="'total' + i" matInput name="total" class='total' id=""
placeholder="Total" style="color:black; font-weight:bold; width: unset;" required>
</div>
where yourPipe is your custom pipe
try [value] property, it will work
<input #username [value]="username.value | currency" [disabled]="true" formControlName="total" [id]="'total' + i" matInput name="total" class='total' id=""
placeholder="Total" style="color:black; font-weight:bold; width: unset;" required>
I tried adding #username [value]="username.value | currency" and its working
In this line of code...
this.loanProductForm.valueChanges.pipe(debounceTime(20)).subscribe((values) => {
(this.loanProductForm.get('products') as FormArray).controls.forEach(group => {
let total = (group.get('quantity').value * group.get('price').value) - group.get('deposit').value;
**group.get('total').setValue(myPipe.transform(total));**
});
});
I have just changed this line in your code group.get('total').setValue(myPipe.transform(total));
and added currency pipe class and call transform()
method and then call this in setValue() of total
form-control.
Update 1
How to include pipe in your component.ts...
import { CurrencyPipe } from './currency.pipe';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ CurrencyPipe]
})
export class AppComponent {
constructor(private currencyPipe: CurrencyPipe) {}
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.