enter code here
In Angular I am not able to capture value of dropdown selected value inside AG-Grid .
I am able to capture all other values in the AG-Grid except dropdown value.
Dropdown is a separate component and it is added via cellRenderer property of columnDefs.
here is my code of parent as well as child component
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Customer } from '../../customer/Models/customer.model';
import { CustomerService } from '../../customer/services/customer.service';
import { CustomerPaymentTermsService } from '../../customerpaymentterms/services/customer-payment-terms.service';
import { CustomerPaymentTerms } from '../../customerpaymentterms/Models/customerpaymentterms.model';
import { ProductService } from '../../Product/Services/product.service';
import { Product } from '../../Product/Models/product.model';
import { ActivatedRoute } from '@angular/router';
import { TradeinitiationService } from '../services/tradeinitiation.service';
import { AddTradeInitiation } from '../Models/AddTradeTransaction.model';
import { Supplier } from '../../customer/Models/supplier.model';
import { getCustomerrequirementlineitems } from '../Models/getCustomerrequirementlineitems.model';
import { SuppliercelleditorcomponentComponent } from '../../suppliercelleditor/suppliercelleditorcomponent/suppliercelleditorcomponent.component';
@Component({
selector: 'app-create-trade-initiation',
templateUrl: './create-trade-initiation.component.html',
styleUrls: ['./create-trade-initiation.component.css']
})
export class CreateTradeInitiationComponent implements OnInit {
id?: number;
gridOptions: any;
customername?: string |undefined;
customerid ?:string;
tradeForm: FormGroup;
customers: Customer[] = [];
customerpaymnetterms: CustomerPaymentTerms[] = [];
products:Product[]=[];
refereno ?:number|undefined;
rowData: any[] = [];
customerSearchControl: FormControl = new FormControl();
customerpaymenttermsSearchControl: FormControl = new FormControl();
filteredCustomers: Customer[] = []; // Initialize filteredCustomers properly filteredCustomers: Customer[] = []; // Initialize filteredCustomers properly
filteredCustomerpaymentterms: CustomerPaymentTerms[] = [];
gridApi: any;
productSearchcontrol :FormControl =new FormControl();
filteredProducts :Product[]=[];
userForm: any;
suppliers:Supplier[]=[];
filteredsupplier :Supplier[]=[];
cuastomerrequorementlineitems :getCustomerrequirementlineitems[]=[];
supplierSearchControl :FormControl=new FormControl();
errorMessage: string | null = null;
model:AddTradeInitiation;
cellClassRules = {
"cell-pass": (params: { value: number; }) => params.value >= 60,
"cell-fail": (params: { value: number; }) => params.value < 60
};
columnDefs = [
{ headerName: 'Product ID', field: 'productId' },
{ headerName: 'Product Name', field: 'name', sortable: true, filter: true, floatingFilter: false },
{ headerName: 'Selling Price', field: 'sellingprice', sortable: true, filter: true, floatingFilter: false , editable: true},
{ headerName: 'Buying Price', field: 'buyingprice', sortable: true, filter: true, floatingFilter: false , editable: true,cellClass: 'editablecell'},
{ headerName: 'Qty', field: 'qty', sortable: true, filter: true, floatingFilter: false , editable: true,
valueGetter: this.defaultQtyValueGetter,
cellClass: 'ecell',
maxWidth: 90,
},
{ headerName: 'Supplier', field: 'Supplier',width:400, sortable: true, filter: true, floatingFilter: false, editable:true, cellRenderer: 'linkRenderer',
cellRendererParams: {
supplierSelected: this.onSupplierSelected.bind(this),
}
},
// Add more columns as needed with floatingFilter
];
defaultQtyValueGetter(params: any): any {
// Example of setting a default value
return params.data.qty ? params.data.qty : 0;
}
onGridReady(params: any): void {
this.gridApi = params.api;
}
constructor(private fb: FormBuilder, private customerService: CustomerService, private customerpaymentservice:CustomerPaymentTermsService, private productservice:ProductService,private route: ActivatedRoute, private tradeinitiationservice:TradeinitiationService) {
this.model={
tInitationid :"",
customerRequirementid:"",
tcustomerid :0,
CustomerPaymentMethodid:0,
transactionInitationStatusid :1,
TInitationDate: '',
}
this.tradeForm = this.fb.group({
tradeInitiationNumber:this.refereno,
date: ['', Validators.required],
customer: ['', Validators.required],
crReferenceNumber: ['', Validators.required],
customerpaymentterms: ['', Validators.required],
product :[''],
sellingprice :[''],
buyingprice :[''],
qty :[''],
supplier:['']
});
this.customerSearchControl.valueChanges.subscribe(value => {
// Filter customers based on the search query
this.filteredCustomers = this.filterCustomers(value);
});
this.customerpaymenttermsSearchControl.valueChanges.subscribe(value => {
// Filter customers based on the search query
this.filteredCustomerpaymentterms = this.filterCustomerpaymentterms(value);
});
this.supplierSearchControl.valueChanges.subscribe(value=>{
this.filteredsupplier =this.fsupplier(value);
})
this.productSearchcontrol.valueChanges.subscribe(value=>{
this.filteredProducts = this.filterProducts(value);
});
}
ngOnInit(): void {
this.gridOptions = {
components: {
linkRenderer: SuppliercelleditorcomponentComponent,
},
// Other grid options
};
this.route.params.subscribe(params => {
// Extract the ID parameter value
this.id = +params['crid'];
this.customername =params['customerName'];
this.tradeinitiationservice.getcustomeridfromcustomername(params['customerName']).subscribe({
next :(response) =>{
console.log("cuatsdhbf bf"+response);
this.customerid =response;
console.log("nnnnnnnnnnnnnnnnnn bf"+this.customerid);
this.tradeForm.get('customer')?.setValue(this.customerid);
}
});
this.tradeinitiationservice.getcustomerrequirementlineitemdetails(params['crid']).subscribe({
next: (response: getCustomerrequirementlineitems[]) => {
console.log(response);
response.forEach(item => {
const rowDataItem = {
productId: item.productid,
name: item.productname,
// map other properties as needed
};
this.rowData.push(rowDataItem);
this.gridApi.setRowData(this.rowData);
});
// If you need to see the results
console.log(this.rowData);
},
error: (err) => {
console.error('Error fetching customer requirement line items', err);
}
});
//alert(this.id);
});
this.tradeinitiationservice.getLastTradeInitiationRefNo().subscribe({
next :(response) =>{
console.log(response);
this.refereno=response;
//alert(this.refereno);
this.tradeForm.patchValue({
tradeInitiationNumber: this.refereno
});
}
});
this.customerService.getallCustomers().subscribe({
next: (response) => {
this.customers = response;
this.filteredCustomers = response; // Initialize filteredCustomers with the full list
}
});
this.customerService.getallsuppliers().subscribe({
next:(response)=>{
this.suppliers =response;
this.filteredsupplier=response;
console.log(this.filteredsupplier);
}
})
this.customerpaymentservice.getAllCustomerPaymnetTerms().subscribe({
next: (response) => {
console.log(response);
this.customerpaymnetterms = response;
this.filteredCustomerpaymentterms = response; // Initialize filteredCustomers with the full list
}
});
this.productservice.getAllProducts().subscribe({
next: (response) => {
this.products = response;
this.filteredProducts = response; // Initialize filteredCustomers with the full list
}
});
}
filterCustomerpaymentterms(value: string): CustomerPaymentTerms[] {
const filterValue = value.toLowerCase();
return this.customerpaymnetterms.filter(customerpaymnetterms => customerpaymnetterms.cPaymentmethodName?.toLowerCase().includes(filterValue));
}
filterProducts(value:string): Product[]{
const filtervalue =value.toLowerCase();
return this.products.filter(products=>products.name?.toLowerCase().includes(filtervalue));
}
filterCustomers(value: string): Customer[] {
const filterValue = value.toLowerCase();
return this.customers.filter(customer => customer.name.toLowerCase().includes(filterValue));
}
fsupplier(value:string):Supplier[]{
const filtervalue =value.toLowerCase();
return this.suppliers.filter(supp=>supp.name?.toLowerCase().includes(filtervalue));
}
addDataToGrid(event:Event):void{
}
onSupplierSelected(event: { value: string, rowIndex: number }) {
console.log('Selected Supplier:', event.value);
alert(event.value);
// Update rowData with the selected supplier value at the specified rowIndex
this.rowData[event.rowIndex].supplierid = event.value;
// Optionally, you can update the grid with the new rowData
if (this.gridApi) {
this.gridApi.setRowData(this.rowData);
}
}
onSubmit() {
//alert("dsfmsdfsd");
//this.model.tInitationid =this.userForm.value.tradeInitiationNumber;
alert(this.id );
alert(this.tradeForm.get('supplier')?.value)
this.model.customerRequirementid = (this.id ?? '').toString();
this.model.TInitationDate =this.tradeForm.get('date')?.value;
this.model.tcustomerid=this.tradeForm.get('customer')?.value;
this.model.CustomerPaymentMethodid =this.tradeForm.get('customerpaymentterms')?.value;
this.model.transactionInitationStatusid =1
this.model.tInitationid = this.tradeForm.get('tradeInitiationNumber')?.value;
this.tradeinitiationservice.createTradeInitationheader(this.model)
.subscribe({
next: (response) => {
if (this.gridApi) {
// Get all row nodes from the grid
this.gridApi.forEachNode((node: { data: any; }) => {
const rowDataItem = {
productId: node.data.productId,
name: node.data.name,
sellingprice: node.data.sellingprice,
buyingprice: node.data.buyingprice,
qty: node.data.qty,
supplierid: node.data.supplierid // Ensure this matches with your grid column definition
};
console.log (rowDataItem);
this.rowData.push(node.data);
});
// Set rowData in your component for further processing
this.rowData = this.rowData;
console.log ( this.rowData );
}
} , error: (error: { status: number; error: string | null; }) => {
if (error.status === 409) { // Check if HTTP status code is 409 Conflict
this.errorMessage = error.error; // Set error message received from the backend
} else {
this.errorMessage = 'An error occurred. Please try again later.'; // Generic error message
}
}
});
}
}
here is my html part of parent componenet.
<div class="container">
<h2 style ="font-weight: bold;">TRADE INITIATION FORM</h2>
<hr/>
<form [formGroup]="tradeForm" (ngSubmit)="onSubmit()" class="form-container">
<div *ngIf="errorMessage" class="error-message mt-3">
{{ errorMessage }}
</div>
<div class="form-row" style="margin-top: 3rem;">
<div class="row">
<div class="col-md-5 col-lg-56">
<mat-form-field appearance="outline" class="form-field custom-width">
<mat-label>Trade Initiation Number</mat-label>
<input matInput formControlName="tradeInitiationNumber" required>
</mat-form-field>
</div>
<div class="col-md-4 col-lg-4">
<mat-form-field appearance="outline" class="form-field">
<mat-label>CR Reference Number</mat-label>
<input matInput [value]="id" readonly>
</mat-form-field>
</div>
<div class="col-md-1 col-lg-1">
<button mat-raised-button color="primary" type="submit">Save</button>
</div>
<div class="col-md-1 col-lg-1">
</div>
<div class="col-md-1 col-lg-1">
<button mat-raised-button color="warning" type="submit">Reset</button>
</div>
</div>
</div>
<div class="form-row">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Date</mat-label>
<input matInput [matDatepicker]="picker" formControlName="date" required>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<div class="form-row">
<div class="row">
<div class="col-md-6 col-lg-6">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Customer</mat-label>
<mat-select formControlName="customer" required>
<!-- Include ngx-mat-select-search inside mat-select -->
<ngx-mat-select-search [formControl]="customerSearchControl"></ngx-mat-select-search>
<!-- Display mat-option for each customer -->
<mat-option *ngFor="let customer of filteredCustomers" [value]="customer.id">
{{ customer.name }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-md-6">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Customer Payment Terms </mat-label>
<mat-select formControlName="customerpaymentterms" required>
<!-- Include ngx-mat-select-search inside mat-select -->
<ngx-mat-select-search [formControl]="customerpaymenttermsSearchControl"></ngx-mat-select-search>
<!-- Display mat-option for each customer -->
<mat-option *ngFor="let customer of filteredCustomerpaymentterms" [value]="customer.cPaymentmethodId
">
{{ customer.cPaymentmethodName }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</div>
</div>
<hr/>
<div class="form-row">
<div class="row">
<div class="col-md-3 col-lg-3">
<mat-form-field class="form-field" appearance ="outline">
<mat-label>Products</mat-label>
<mat-select formControlName="product" >
<ngx-mat-select-search [formControl]="productSearchcontrol" > </ngx-mat-select-search>
<mat-option *ngFor="let product of filteredProducts" [value]="product.productId
"> {{product.name}} </mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-md-2">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Qty</mat-label>
<input matInput formControlName="qty">
</mat-form-field>
</div>
<div class="col-md-2">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Selling Price</mat-label>
<input matInput formControlName="sellingprice">
</mat-form-field>
</div>
<div class="col-md-2">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Buying Price</mat-label>
<input matInput formControlName="buyingprice">
</mat-form-field>
</div>
<div class="col-md-2">
<mat-form-field class="form-field" appearance ="outline">
<mat-label>Supplier</mat-label>
<mat-select formControlName="supplier" >
<ngx-mat-select-search [formControl]="supplierSearchControl" > </ngx-mat-select-search>
<mat-option *ngFor="let sup of filteredsupplier" [value]="sup.sId
"> {{sup.name}} </mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-md-1">
<button mat-raised-button color="primary" type="button" class="custom-button" (click)="addDataToGrid($event)">+</button>
</div>
</div>
</div>
<div class="ag-theme-alpine" >
<ag-grid-angular
style="width:1300px; height: 300px; border: 1px solid black;"
class="ag-theme-alpine" [rowHeight]="55"
[rowData]="rowData"
[columnDefs]="columnDefs" (gridReady)="onGridReady($event)" [gridOptions]="gridOptions">
</ag-grid-angular>
</div>
<div>
<p>Percentage: {{ 56 | number:'1.2-3' }}</p>
</div>
</form>
</div>
here is the .ts and html file of child component.
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { ICellEditorAngularComp } from 'ag-grid-angular';
import { ICellEditorParams } from 'ag-grid-community';
import { CustomerService } from '../../customer/services/customer.service';
import { Supplier } from '../../customer/Models/supplier.model';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-suppliercelleditorcomponent',
templateUrl: './suppliercelleditorcomponent.component.html',
styleUrls: ['./suppliercelleditorcomponent.component.css']
})
export class SuppliercelleditorcomponentComponent implements ICellEditorAngularComp, OnInit {
params!: ICellEditorParams;
selectedSupplier!: string;
supplierSearchControl :FormControl=new FormControl();
filteredsupplier:Supplier[]=[];
tradeForm1: FormGroup;
suppliers :Supplier[]=[];
@Output() supplierSelected = new EventEmitter<any>();
onDropdownClick(){
alert("zsdnsdbfds");
}
constructor(private customerService: CustomerService, private fb: FormBuilder) {
this.tradeForm1 = this.fb.group({
supplier:['']
});
this.supplierSearchControl.valueChanges.subscribe(value => {
// Filter customers based on the search query
this.filteredsupplier = this.fsupplier(value);
});
}
fsupplier(value:string){
const filtervalue =value.toLowerCase();
return this.suppliers.filter(supp=>supp.name?.toLowerCase().includes(filtervalue));
}
agInit(params: ICellEditorParams<any, any, any>): void {
this.params=params;
this.selectedSupplier = this.params.value;
}
getValue() {
return this.selectedSupplier;
}
refresh?(params: ICellEditorParams<any, any, any>): void {
throw new Error('Method not implemented.');
}
afterGuiAttached?(): void {
}
isPopup?(): boolean {
return false;
}
getPopupPosition?(): 'over' | 'under' | undefined {
throw new Error('Method not implemented.');
}
isCancelBeforeStart?(): boolean {
return false;
}
isCancelAfterEnd?(): boolean {
return false;
}
focusIn?(): void {
throw new Error('Method not implemented.');
}
focusOut?(): void {
throw new Error('Method not implemented.');
}
ngOnInit(): void {
this.customerService.getallsuppliers().subscribe({
next: (response) => {
console.log(response);
this.suppliers = response;
this.filteredsupplier = response; // Initialize filteredCustomers with the full list
}
});
}
onSupplierSelected(event: any): void {
this.selectedSupplier = event.value;
alert(this.selectedSupplier);
const rowIndex = this.params.rowIndex;
alert(rowIndex);
this.supplierSelected.emit({ value: this.selectedSupplier, rowIndex });
}
}
here is the html code of child componenet.
<form [formGroup]="tradeForm1" style="width: 10px;height:10px">
<mat-form-field class="form-field" appearance="outline">
<mat-label>supplier</mat-label>
<mat-select formControlName="supplier" (selectionChange)="onSupplierSelected($event)">>
<ngx-mat-select-search [formControl]="supplierSearchControl"></ngx-mat-select-search>
<mat-option *ngFor="let sup of filteredsupplier" [value]="sup.sId">
{{sup.name}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
on button click inside main component I am able to capture all the values of ag-grid except those in dropdown. conole.log is showing all values inside ag-grid except dropdown supplier ..it is showing undefined
here is the console.log