J'ai besoin d'ajouter monnaie code> tuyau à mon Total de colonne code>, mais le problème est qu'il s'agit d'une entrée entrée code>, comment puis-je faire cela? 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
})
});
});
}
}
3 Réponses :
Vous pouvez utiliser une propriété p> où Yourpipe strong> est votre Tuyau sur mesure P> P>
Désolé, mais ça ne fonctionne pas. Sa donnant moi une erreur ne peut pas lire la propriété 'valeur' de null code>
Comment savoir angulaire quel total code> pour obtenir, parce que c'est un tableau
Pouvez-vous publier votre groupe de formes parent? Selon votre question, j'ai posté la réponse. Je peux modifier la même chose si le groupe de formulaire parent auquel vous avez poussé le groupe de formulaires enfant est présent dans la question.
J'ai posté mes fichiers complets, composant code> et Modèle code> S'il vous plaît jeter un oeil maintenant
Désolé, mais cela ne fonctionne toujours pas, le tuyau est là quand je n'ai pas sélectionné le produit, mais dès que je sélectionne un produit de liste déroulante, il supprime le tuyau et un nombre normal est écrit là-bas.
Essayez la propriété [valeur], il fonctionnera
<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>
@Lint essayez cette solution et faites-moi savoir
Dans cette ligne de code ...
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) {}
// ...
}
J'ai essayé le group.get ('Total'). SetValue (currencyPipe.transform (total)); code> mais son erreur de donneur, La transformation de la propriété n'existe pas de type currencyppe code>
@Lint Consultez mon Mise à jour-1 Code> Réponse et ajoutez un tuyau de devise correctement au composant, puis vous devez l'injecter dans constructeur (), vous pouvez alors accéder à transformer () code>
Maintenant, je reçois cette erreur newloancomponent_host.ngfactory.js? [SM]: 1 Erreur NullInjectorError: staticinjectorerror (Appmodule) [NewLoancomomponent -> Currencype]: StaticinjectorError (plate-forme: noyau) [NewLoancomomponent -> Currencype]: NullinjectorError: Aucun fournisseur de Currencype! Code>
avez-vous add CurrencyPipe au formidateur de module ou non
Non, comment puis-je faire ça?
Oui tu dois faire ça
D'accord, il a commencé à travailler, maintenant le problème est qu'il affiche la valeur dans $ code> alors que j'ai besoin de la valeur dans kes code> devise, comment faire cela?
Laissez-nous Continuez cette discussion en chat .
Est-ce rendu avec un * ngfor?
Non, la nouvelle ligne est ajoutée lorsque l'utilisateur clique sur le bouton
Ajouter CODE>