How to set default value for PrimeNG p-dropdown












5















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









share|improve this question





























    5















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









    share|improve this question



























      5












      5








      5


      1






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









      share|improve this question
















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






      angular5 primeng primeng-dropdowns






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 1 at 11:35







      Bhagvat Lande

















      asked Apr 3 '18 at 6:41









      Bhagvat LandeBhagvat Lande

      1721217




      1721217
























          4 Answers
          4






          active

          oldest

          votes


















          2














          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






          share|improve this answer


























          • thanks for help , but it didn't works

            – Bhagvat Lande
            Apr 3 '18 at 12:19











          • Sorry, is it better ?

            – Antikhippe
            Apr 3 '18 at 14:01











          • For above cli return error as unexpected token

            – Bhagvat Lande
            Apr 3 '18 at 14:08













          • See again my edit and Plunker

            – Antikhippe
            Apr 3 '18 at 14:09











          • thakhs i am testing give me minutes

            – Bhagvat Lande
            Apr 3 '18 at 14:16





















          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






          share|improve this answer































            0















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






            share|improve this answer

































              0














              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






              share|improve this answer
























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49623774%2fhow-to-set-default-value-for-primeng-p-dropdown%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                2














                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






                share|improve this answer


























                • thanks for help , but it didn't works

                  – Bhagvat Lande
                  Apr 3 '18 at 12:19











                • Sorry, is it better ?

                  – Antikhippe
                  Apr 3 '18 at 14:01











                • For above cli return error as unexpected token

                  – Bhagvat Lande
                  Apr 3 '18 at 14:08













                • See again my edit and Plunker

                  – Antikhippe
                  Apr 3 '18 at 14:09











                • thakhs i am testing give me minutes

                  – Bhagvat Lande
                  Apr 3 '18 at 14:16


















                2














                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






                share|improve this answer


























                • thanks for help , but it didn't works

                  – Bhagvat Lande
                  Apr 3 '18 at 12:19











                • Sorry, is it better ?

                  – Antikhippe
                  Apr 3 '18 at 14:01











                • For above cli return error as unexpected token

                  – Bhagvat Lande
                  Apr 3 '18 at 14:08













                • See again my edit and Plunker

                  – Antikhippe
                  Apr 3 '18 at 14:09











                • thakhs i am testing give me minutes

                  – Bhagvat Lande
                  Apr 3 '18 at 14:16
















                2












                2








                2







                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






                share|improve this answer















                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







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Apr 5 '18 at 11:56

























                answered Apr 3 '18 at 8:11









                AntikhippeAntikhippe

                3,45911332




                3,45911332













                • thanks for help , but it didn't works

                  – Bhagvat Lande
                  Apr 3 '18 at 12:19











                • Sorry, is it better ?

                  – Antikhippe
                  Apr 3 '18 at 14:01











                • For above cli return error as unexpected token

                  – Bhagvat Lande
                  Apr 3 '18 at 14:08













                • See again my edit and Plunker

                  – Antikhippe
                  Apr 3 '18 at 14:09











                • thakhs i am testing give me minutes

                  – Bhagvat Lande
                  Apr 3 '18 at 14:16





















                • thanks for help , but it didn't works

                  – Bhagvat Lande
                  Apr 3 '18 at 12:19











                • Sorry, is it better ?

                  – Antikhippe
                  Apr 3 '18 at 14:01











                • For above cli return error as unexpected token

                  – Bhagvat Lande
                  Apr 3 '18 at 14:08













                • See again my edit and Plunker

                  – Antikhippe
                  Apr 3 '18 at 14:09











                • thakhs i am testing give me minutes

                  – Bhagvat Lande
                  Apr 3 '18 at 14:16



















                thanks for help , but it didn't works

                – Bhagvat Lande
                Apr 3 '18 at 12:19





                thanks for help , but it didn't works

                – Bhagvat Lande
                Apr 3 '18 at 12:19













                Sorry, is it better ?

                – Antikhippe
                Apr 3 '18 at 14:01





                Sorry, is it better ?

                – Antikhippe
                Apr 3 '18 at 14:01













                For above cli return error as unexpected token

                – Bhagvat Lande
                Apr 3 '18 at 14:08







                For above cli return error as unexpected token

                – Bhagvat Lande
                Apr 3 '18 at 14:08















                See again my edit and Plunker

                – Antikhippe
                Apr 3 '18 at 14:09





                See again my edit and Plunker

                – Antikhippe
                Apr 3 '18 at 14:09













                thakhs i am testing give me minutes

                – Bhagvat Lande
                Apr 3 '18 at 14:16







                thakhs i am testing give me minutes

                – Bhagvat Lande
                Apr 3 '18 at 14:16















                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






                share|improve this answer




























                  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






                  share|improve this answer


























                    0












                    0








                    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






                    share|improve this answer













                    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







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Sep 10 '18 at 1:44









                    chouchou

                    1




                    1























                        0















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






                        share|improve this answer






























                          0















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






                          share|improve this answer




























                            0












                            0








                            0








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






                            share|improve this answer
















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







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Sep 21 '18 at 12:37

























                            answered Sep 12 '18 at 7:48









                            Murat YıldızMurat Yıldız

                            7,06753846




                            7,06753846























                                0














                                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






                                share|improve this answer




























                                  0














                                  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






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    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






                                    share|improve this answer













                                    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







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 23 '18 at 9:49









                                    makkasimakkasi

                                    1,11412035




                                    1,11412035






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49623774%2fhow-to-set-default-value-for-primeng-p-dropdown%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Paul Cézanne

                                        UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

                                        Angular material date-picker (MatDatepicker) auto completes the date on focus out