Vaibhav Sawant
Vaibhav Sawant

Reputation: 361

Angular 2 : p-dropdown default value selection from options which are coming from API

In Angular 2, P-dropdown is mapped with object which is populated from web API call. And after API call, ngModel is set to some value which is present in dropdown. But, still no value is shown as default and it still show placeholder value.

HTML

<div *ngIf="dropdownDataLoaded" style="display: inline-block">
                        <span class="dropdown" style="margin-left: 126px;">
                            <p-dropdown [options]="countryOptions" placeholder="Select" [(ngModel)]="selectedCountryValue" inputStyleClass="dropdown" optionLabel="name" (onChange)="onCountryChange($event)"></p-dropdown>
                        </span>
                    </div>

Component :

this.dropdownDataLoaded = false;

setTimeout(() => {
    this.databaseService.getCountryList().subscribe((countryList: IDropdownElement[]) => {
       this.countryOptions = countryList;
       this.dropdownDataLoaded = true;
       this.selectedCountryValue = {
        "name": "USA"
       };
      }

IDropdownElement Model :

export interface IDropdownElement {
  name: string;
  id: string;
  type: string;
  code: string;
}

Also, referred below link but no luck.

How to set default value for PrimeNG p-dropdown

Upvotes: 1

Views: 9248

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

ngModel binds by reference, not value.

So you need to have it pointing to the same object as is in your list.

Change this:

this.selectedCountryValue = {
        "name": "USA"
       };

To this:

this.selectedCountryValue = this.countryOptions.find(country => country.name === 'USA');

Or use compareWith directive, read more here: https://angular.io/api/forms/SelectControlValueAccessor

Upvotes: 3

Related Questions