Home > Mobile >  How can I preset a value by default in p-dropdown?
How can I preset a value by default in p-dropdown?

Time:10-29

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

CodePudding user response:

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
    },

CodePudding user response:

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