Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value for PrimeNG p-dropdown

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 });
        }
    }
});
like image 424
Bhagvat Lande Avatar asked Apr 03 '18 06:04

Bhagvat Lande


7 Answers

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.

like image 84
user1662833 Avatar answered Sep 22 '22 23:09

user1662833


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

like image 28
Antikhippe Avatar answered Sep 25 '22 23:09

Antikhippe


Replacement solution, try using:

[placeholder]="yourSelectedObject.Field"
like image 27
user7070123 Avatar answered Sep 21 '22 23:09

user7070123


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;  

Hope this helps...

like image 39
Murat Yıldız Avatar answered Sep 25 '22 23:09

Murat Yıldız


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

like image 40
makkasi Avatar answered Sep 21 '22 23:09

makkasi


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'

like image 37
GustavoTM Avatar answered Sep 22 '22 23:09

GustavoTM


<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.

like image 22
Garvit Jain Avatar answered Sep 23 '22 23:09

Garvit Jain