0

The p-dropdown below is reading json data from API. Among the data values, I want to set up "apple" by default. Currently, in the p-dropdown, the first thing users can see is the placeholder value (i.e "Select a Product").

How can I preset a default value in p-dropdown? Any help or advice, please?

                <p-dropdown
                  [options]="products"
                  optionLabel="productName"
                  optionValue="productId"
                  placeholder="Select a Product"
                  [filter]="true"
                  filterBy="productName"
                ></p-dropdown>
[
    {
        productName: "apple",
        productId: 1
    },
    {
        productName: "banana",
        productId: 2
    },
    {
        productName: "watermelon",
        productId: 3
    },
]
JBC
  • 33
  • 5

1 Answers1

2

You can use an ngModel to tie your current selectedItem to the dropdown selected item and viceversa.

<p-dropdown
  [options]="products"
  optionLabel="productName"
  optionValue="productId"
  placeholder="Select a Product"
  [filter]="true"
  filterBy="productName"
  [(ngModel)]="selectedProduct" // Add this line
></p-dropdown>

It's important that you do add that property to your Angular component, in order to be able to use it.

Edit: Here's an example for your component:

interface Product {
  productId: number;
  productName: string;
}

@Component({
  ...
})
export class DropdownDemo {
  public products: Product[] = [
    {
      productName: 'apple',
      productId: 1,
    },
    {
      productName: 'banana',
      productId: 2,
    },
    {
      productName: 'watermelon',
      productId: 3,
    },
  ];
  public selectedProduct: Product; // This is what you'd use for your [(ngModel)]
}

Let me know if that helped!

saguirrews
  • 280
  • 1
  • 7