This is an example of code for p-dropdown.
// product.component.html
<p-dropdown
[options]="products"
optionLabel="productName"
placeholder="Select a product"
>
</p-dropdown>
This is json data I am getting from API. In the p-dropdown
, the productName
is successfully shown.
// products data
[
{
productName: "Apple",
productId: 1
},
{
productName: "Banana",
productId: 2
},
{
productName: "Peach",
productId: 3
},
]
My question is, when users select the product, how to store productId
from the selected product to a newly created variable in ts? There are multiple p-dropdown
in p-table
's rows so I want to store the multiple productId
selected values into an array selectedProductId
.
// product.component.ts
// How to store productID from the selected product to a newly created variable in ts?
selectedProductId!: any[];
CodePudding user response:
I suggest you to read the documentation at https://www.primefaces.org/primeng-v13/dropdown
In your case it seems be possible do that:
in your.component.html:
<p-dropdown
(onChange)="selectProduct($event?.value)"
[options]="products"
optionLabel="productName"
optionValue="productId">
</p-dropdown>
in your.component.ts:
selectedProductId: number[] = [];
selectProduct(id: number) {
if (!this.selectedProductId.includes(id))
this.selectedProductId.push(id);
}