0

I am trying to preset a default value in the below p-dropdown.

[ item.component.html ]

<ng-template pTemplate="body" let-newItem>
    <tr>
        <td>
            <p-tableCheckbox [value]="newItem"></p-tableCheckbox>
        </td>
        <td>{{ newItem.Key }}</td>
        <td>{{ newItem.Value }}</td>
        <td>
            <p-dropdown
                [options]="itemLists"
                optionLabel="name"
                optionValue="id"
                placeholder="Select an item"
                [filter]="true"
                filterBy="name"
                (onChange)="selectItem($event.value)"
            ></p-dropdown>
        </td>
    </tr>
</ng-template>

I am getting json data from API and the data looks like

[
    {
        name: "clutch",
        id: 1
    },
    {
        name: "hat",
        id: 2
    },
    {
        name: "jeans",
        id: 3
    },
]

This is a part of the .ts file.

[ item.component.ts ]

export class ItemComponent implements OnInit {
    itemLists: any[] = [];
    selectedId: any[] = [];

    constructor(
        private itemService: ItemService
    ){}

    ngOnInit(): void {
        this.getItems();
    }

    getItems() {
        this.itemService.getItemLists().subscribe(
          (res) => {
            this.itemLists = res;
          },
          (err) => {
            console.log(err);
          }
        );
    }

    selectItem(id: any){
        this.selectedId.push(id);
    }
}

When users open the template and go to the p-dropdown, I want "hat" to be already selected by default. How can I make this? Any help, please

R. Richards
  • 24,603
  • 10
  • 64
  • 64
JBC
  • 33
  • 5

2 Answers2

0

using the two-way biding to set the default value

ex:

<p-dropdown
                [options]="itemLists"
                optionLabel="name"
                optionValue="id"
                placeholder="Select an item"
                [filter]="true"
                filterBy="name"
                (onChange)="selectItem($event.value)"
                [(ngModel)]="defaultValue" <!-- the default value here -->
            ></p-dropdown>

ex:

defaultValue= {
        name: "clutch",
        id: 1
    },
GOD
  • 1
  • 1
  • In `getItems()`, I defined `this.defaultValue = this.itemLists.find((x) => x.id == 2)`. Next, I put `[(ngModel)]="defaultValue"` in the `p-dropdown`. However, this does not work as expected. Is this what you mention? Or am I getting it wrong? – JBC Oct 27 '22 at 18:34
  • let's see my demo: https://stackblitz.com/edit/primeng-dropdown-demo-13cxpr?file=src%2Fmy-service.service.ts – GOD Oct 27 '22 at 19:41
0
    getItems() {
    this.itemService.getItemLists().subscribe(
      (res) => {
        this.itemLists = res;
        this.selectItem(theIdOfYourDefaultItem);
      },
      (err) => {
        console.log(err);
      }
    );
}
Taha Zgued
  • 1,088
  • 12
  • 18