【问题标题】:How to set default value for PrimeNG p-dropdown如何为 PrimeNG p-dropdown 设置默认值
【发布时间】:2018-04-03 06:41:41
【问题描述】:

我在我的 angular5 应用程序中使用 PrimeNG。我对 p-dropdown 有疑问

问题

我有用于显示国家/地区的 p 下拉菜单。我在那里正确绑定了选择选项,它工作正常(此数据来自 api),但我需要将此 p-dropdown 的默认选定选项设置为“印度”。

我将 ng-model 值设置为 India,但它不起作用。

我的 dummy.component.html 代码

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

我的 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


    【解决方案1】:

    这可能是由于 PrimeNG 不知道将“selectedCountry”绑定到哪个字段,即。下拉控件的“国家”模型具有更多的键和值属性。

    就我而言,我必须明确地“告诉”每个下拉字段值的属性是"value"。我为此使用了p-dropdown dataKey 属性。

    所以,在我的下拉控件中,我添加了如下内容:

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

    您可以阅读更多here

    【讨论】:

      【解决方案2】:

      尝试替换

      this.applicant.country = 'India';
      

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

      编辑

      从 API 获取数据后,显示您的 p-dropdown

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

      Plunker

      【讨论】:

      • 对不起,好点了吗?
      • 谢谢我正在测试给我几分钟
      • hie,我根据 urs plunker 进行了更改,它在静态数据方面效果很好,但在我的情况下,国家来自 api,为此它不起作用,请帮我摆脱困境这里
      • 你的 api 中result 的输出是什么?
      • @ Antikhippe 这是 josn 的数组 [{ Id:1, name:India }, Id:2, name: srilanka }] 我检查了一下,我认为控制器不会等待完成所有结果并执行下一条语句,即默认发送国家“印度”
      【解决方案3】:

      您可以使用 ngModel 设置 PrimeNG Dropdown 的默认值,如下所示:


      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
      


      如果因为版本问题没有修复,试试这个:

      this.cities.value = this.selectedCity;  
      

      希望这会有所帮助...

      【讨论】:

        【解决方案4】:

        替换解决方案,尝试使用:

        [placeholder]="yourSelectedObject.Field"
        

        【讨论】:

          【解决方案5】:

          我的解决方案是在设置表单字段(ngModel 或 formControl)之前将国家/地区加载到控制器中。还要保持相同类型的密钥。表单控件不要使用数字,列表不要使用字符串:

          // 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)
          

          在上面的代码中 this.user.city_id 和 city.id 具有相同的类型号

          【讨论】:

            【解决方案6】:

            我也遇到了这个问题,经过几分钟的调试,我发现这个问题的一些常见原因可能是:

            1) 类型不匹配 - 下拉菜单可以绑定整数,[(ngModel)] 属性可以是字符串。

            例如:

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

            在哪里

            countries = [1,2,3]
            

            selectedCountry = '1'
            

            2) 大写 - 小写 - 下拉列表可以绑定到小写字符串,并且 [(ngModel)] 属性可以是大写或两者的组合。

            例如:

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

            selectedCountry = 'united states'
            

            必须完全匹配才能按预期工作,在本例中为 'United States'

            【讨论】:

            • 这条线索帮助我理解了问题(尤其是#1)。谢谢!通常我使用 SelectItem 来映射选定但在我的情况下,当下拉值是数字(并且 onmodelchange 事件返回数字)时,使用 SelectItem 是没有意义的。我将 selectedItem 切换为“any”并使用 value/id 更改选择。
            【解决方案7】:

            我使用这个解决方案来解决这个问题

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

            它在primeng 6.1.3工作

            【讨论】:

              【解决方案8】:

              我刚刚遇到了类似的问题。 我用 html 属性“optionLabel”解决了这个问题。如果我们阅读 PrimeNG 文档,它会说:当使用任意对象而不是 SelectItems 作为选项时,选项的标签字段的名称。

              Official documentation

              希望对你有帮助

              【讨论】:

                【解决方案9】:

                PrimgNg 中的更新

                在Primeng中为下拉菜单设置默认值时需要小心。

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

                country 应该是 number 而不是字符串。

                如果是字符串,您可以对其进行类型转换。

                country: Number("1");
                

                【讨论】:

                  【解决方案10】:

                  您的“selectedCountry”必须具有您的国家元素具有的所有键

                  【讨论】:

                    【解决方案11】:

                    你也可以试试这个。假设您的下拉列表如下所示:

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

                    ngOnInit,这样做:

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

                    其中 select 和 id 应该是默认标签和值。

                    【讨论】:

                      【解决方案12】:
                      <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>
                      

                      只需指定名称 optionLabel 和 optionValue。

                      数据为{ label: this.cnt[i].name, value: this.cnt[i].id }

                      所以标签键的值将用于显示,值键的值将用于ngModel。

                      【讨论】:

                        【解决方案13】:

                        Angular 13 和 PrimeNg 13。

                        答案很简单:

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

                        诀窍是设置 this.isReady 布尔值,然后将 *ngIf 放在 p-dropdown 上。下拉列表似乎没有响应代码方面的值变化,因此这会强制它在您选择哪个项目是当前值之前不显示下拉列表。

                        【讨论】:

                          猜你喜欢
                          • 2022-06-27
                          • 2021-03-02
                          • 1970-01-01
                          • 2019-12-15
                          • 1970-01-01
                          • 1970-01-01
                          • 2021-04-23
                          • 2020-12-20
                          • 2017-09-11
                          相关资源
                          最近更新 更多