How to set default value for PrimeNG p-dropdown
Asked Answered
S

15

30

I am using PrimeNG in my angular5 app. I have issue with p-dropdown

Question

I have p-dropdown for showing countries. I bind the select options correctly there it works fine (this data coming from api), but I need to set default selected option for this p-dropdown as "India".

I set up ng-model value as India but it didn't work.

my dummy.component.html code

<div class="form-group col-md-2">
    <div>
        <label for="inputEmail4"> Select Country</label>
        <span style="color:red">*</span>
    </div>
    <p-dropdown name="country" [options]="countries" [(ngModel)]="applicant.country" placeholder="select country"
            (onChange)="getStatebyCountry(applicant.country,$event)" #country="ngModel" required>
    </p-dropdown>
    <span *ngIf="country.invalid && (country.dirty || country.touched)">
        <span [hidden]="!country.hasError('required')" style="color:#ffa500">country is mandatory</span>
    </span>
</div>

my dummy.component.ts

export class dummyComponent implements OnInit {
    //variable declaration scope for all controller function
    applicant: any = {};

    country: string; constructor() { }

    ngOnInit() {
        this.applicant.country = 'India';
    } 
    this.countries = [];
    // this.countries.push({ label: 'Select Country', value: '' });
    //getallcountries
    this.UserService.getallcountries().subscribe(result => {
    console.log("countries" + result);
    this.cnt = result;
    for (let i = 0; i <= this.cnt.length; i++) {
        if (this.cnt[i].id === 1) {
            this.countries.push({ label: this.cnt[i].name, value: this.cnt[i].id });
        }
    }
});
Sicyon answered 3/4, 2018 at 6:41 Comment(0)
W
22

This may be caused if PrimeNG doesn't know to which field to bind the "selectedCountry", ie. your "countries" model for the dropdown control has more then key and value properties.

In my case, I had to explicitly "tell" to each dropdown field that the property for values is "value". I used the p-dropdown dataKey property for this.

So, in my dropdown control, I added something like this:

<p-dropdown dataKey="value" ></p-dropdown>

You can read more here.

Wear answered 14/11, 2019 at 9:51 Comment(0)
M
8

Try to replace

this.applicant.country = 'India';

with

this.applicant = {country: 'India'};

Edit

Display your p-dropdown once you got the data from your API.

<div *ngIf="dataLoaded">
  <p-dropdown [options]="countries" [(ngModel)]="applicant.country"></p-dropdown>
</div>

See Plunker

Mcnelly answered 3/4, 2018 at 8:11 Comment(10)
Sorry, is it better ?Mcnelly
thakhs i am testing give me minutesSicyon
hie , i made changes as per urs plunker its works great with static data , but in my case countrie is coming from api , for this it didn't work , can please help me get out me from hereSicyon
What is the output of result from your api ?Mcnelly
@ Antikhippe It's array of josn [{ Id:1, name:India }, Id:2, name: srilanka }] I checked the thing , i thought controller doesn't wait for the finish get all result and execute next statement i.e default sent country "India"Sicyon
Ok, I understand. Check my Edit and new Plunker.Mcnelly
thank you very much for urs reply , i'm just checking please stay here if possibleSicyon
@ Antikhippe hie met thank you very much for vert help , really appreciate yours efforts , i need to make disable this dropdown on india selected , i read the docs but there is no attribute for this , can you please help hereSicyon
You're welcome. Do you mean you need to disable the dropdown if India is selected ?Mcnelly
Let us continue this discussion in chat.Sicyon
C
5

You can set default value of PrimeNG Dropdown by using ngModel as shown on the following approach:


***component.html:***
<p-dropdown [options]="cities" name="selectedCity" [(ngModel)]="selectedCity"></p-dropdown>

***component.ts:***
selectedCity: string = 1; //Id value of the City to be selected

If it is not fixed due to version problems, try this:
this.cities.value = this.selectedCity;  
Chinkapin answered 12/9, 2018 at 7:48 Comment(0)
Z
5

Replacement solution, try using:

[placeholder]="yourSelectedObject.Field"
Zaid answered 5/1, 2021 at 17:22 Comment(0)
V
3
<p-dropdown name="country"
    
    optionLabel="label"
    optionValue="value"

    [options]="countries"
    [(ngModel)]="applicant.country"
    placeholder="select country"
    (onChange)="getStatebyCountry(applicant.country,$event)"     
    #country="ngModel" required>
</p-dropdown>

Just specify name optionLabel and optionValue.

The data is { label: this.cnt[i].name, value: this.cnt[i].id }

So the label key's value will be used for display and value key's value will be used in ngModel.

Vtarj answered 28/8, 2021 at 6:18 Comment(0)
A
2

I been having this issue too and after several minutes debugging, I have found that some of the common reason for this problem can be:

1) Type mismatch - The drop-down can be binding to integers and [(ngModel)] property can be an string.

For example:

<p-dropdown [options]="countries" [(ngModel)]="selectedCountry"></p-dropdown>

Where

countries = [1,2,3]

and

selectedCountry = '1'

2) Uppercase- Lower-Case - The drop-down can be binding to an string that is lower case and [(ngModel)] property can be on Uppercase or a combination of both.

For example:

countries = ['United States', 'England', 'Bolivia']

and

selectedCountry = 'united states'

It has to be an exact match to work as expected, in this case 'United States'

Awed answered 28/8, 2019 at 18:53 Comment(1)
That clue helped me to understand the problem (especially #1).Thanks! Usually I'm using SelectItem to map selected but in my case when dropdown value is number (and onmodelchange event returns number) SelectItem using is pointless. I switched selectedItem to 'any' and go with value/id to change selection.Overrefinement
U
1

My solution was to have the countries loaded in the controller before setting the form field (ngModel or formControl). Also keep the same type of the key. Don't use number for the form control and string for the list:

// first get the cities from the server
response.cities.forEach(city => {
                      this.dropdowns['cities'].push({ value: city.id, label: element.city }); });

// when setting the form
city_id: new FormControl(this.user.city_id)

In the code above this.user.city_id and city.id has the same type number

Unseasoned answered 23/11, 2018 at 9:49 Comment(0)
U
1

Angular 13 with PrimeNg 13.

The answer was simple:

<p-dropdown *ngIf="isReady" [options]="offices" [(ngModel)]="selectedOffice" optionLabel="name" ></p-dropdown>

Component.ts
this.selectedOffice = this.offices.find(o => o.id === id);
this.isReady = true;

The trick was setting the this.isReady boolean and then putting the *ngIf on the p-dropdown. The dropdown does not seem to respond to changes in value from the code side, so this forces it to no display the dropdown until you have selected which item is the current value.

Uncover answered 2/2, 2022 at 1:8 Comment(0)
B
1

primeng dropdown doesn't know what value to set if you don't add 'optionValue'. To set a default value, we must add optionValue="value" in p-dropdown like this:

<p-dropdown [options]="cities" [(ngModel)]="selectedCityCode" optionLabel="name" formControlName="city" optionValue="value"></p-dropdown>

In .ts file:

FormGroup.controls.city.setValue('cityCode');

Hope this helps someone.

Bargeman answered 8/11, 2022 at 9:48 Comment(0)
Q
0

I use this solution to fix this

html:

<p-dropdown name="country" [options]="countries" [(ngModel)]="country" placeholder="select country" (onChange)="changeCountry()"></p-dropdown>

ts:

    public country;
    public countries;
    ngOnInit() {
        this.applicant.country = 'India';
        this.getCountry().then(()=>{
          this.country = this.applicant.country
        })
    } 
    getCountry(){
      return new Promise( (resolve,reject) => {
        this.UserService.getallcountries().subscribe(result => {
          this.cnt.forEach(element => {
            this.countries.push({
              label: element.name,
              value: element.id
            });
          });
          resolve();
        }, error =>{
          reject();
        });
      })          
    }
    changeCountry(){
     this.country = this.applicant.country;
    }

it work at primeng 6.1.3

Quartered answered 10/9, 2018 at 1:44 Comment(0)
R
0

Update in PrimgNg

While setting default value for dropdown in Primeng need to be little careful.

<p-dropdown name="country" [options]="countries" [(ngModel)]="country" placeholder="select country" (onChange)="changeCountry()"></p-dropdown>

country should be a number not string.

You can typecast it, if it is a string.

country: Number("1");
Ragout answered 26/4, 2019 at 12:31 Comment(0)
F
0

I just had a similar problem. I solved this with the html attribute "optionLabel". If we read the PrimeNG documentation it says this : Name of the label field of an option when an arbitrary objects instead of SelectItems are used as options.

Official documentation

Hope it helps

Fit answered 17/9, 2019 at 14:13 Comment(0)
A
0

your 'selectedCountry' must have all key that your countries element have

Atone answered 9/6, 2021 at 23:23 Comment(0)
C
0

You can also try this. Let's say, your dropdown looks like this:

     <p-dropdown
      class="iteration-dropdown"
      [options]="cities"
      [(ngModel)]="selectedCity"
      name="selectedCity"
      (onChange)="loadIterationFeatures()"
     ></p-dropdown>

On ngOnInit, do this:

 this.selectedCity = this.select;
 this.cities = [{label: this.select, value: this.id}]

Where select and id are supposedly the default label and value.

Craft answered 17/8, 2021 at 4:5 Comment(0)
T
0
<p-dropdown
--------
[placeholder]="yourArray[1].value"
--------
/>
</p-dropdown>
Toandfro answered 24/7 at 6:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.