-1

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[];
JBC
  • 33
  • 5
  • 1
    Please don't use `any`; have you seen [basic types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html) in the handbook? – kelsny Oct 25 '22 at 15:51

1 Answers1

0

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);
}
skink
  • 5,133
  • 6
  • 37
  • 58
Luca Angrisani
  • 359
  • 3
  • 13