How to set default value for PrimeNG p-dropdown

為{幸葍}努か 提交于 2019-11-28 12:06:14

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

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

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

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

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");

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!