如何为PrimeNG的p-dropdown设置默认值

28

我在我的Angular5应用程序中使用PrimeNG。 我在p-dropdown方面遇到了问题。

问题

我有一个用于显示国家的p-dropdown。 我正确地绑定了选择选项,它可以正常工作(这些数据来自api),但是我需要将默认选定选项设置为“印度”。

我将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 });
        }
    }
});
14个回答

19

如果PrimeNG不知道将"selectedCountry"绑定到哪个字段,即你的下拉框控件的"countries"模型具有多个键和值属性,则可能会导致此问题。

在我的情况下,我必须明确地告诉每个下拉框字段,其用于值的属性是"value"。我使用了属性来实现这一点。

因此,在我的下拉框控件中,我添加了类似于以下内容:

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

你可以在这里阅读更多内容。


8
尝试替换

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


抱歉,这样好一些吗? - Antikhippe
谢谢,我正在测试,请给我几分钟。 - Bhagvat Lande
嗨,我根据您的 Plunker 进行了更改,它在静态数据方面运行得很好,但在我的情况下,国家是来自 API 的,因此它无法工作,您能帮助我摆脱这里吗? - Bhagvat Lande
@Antikhippe 这是一个 JSON 数组 [{ Id:1, name:India }, { Id:2, name: srilanka }]。我检查了一下,我认为控制器不会等待获取所有结果并执行下一条语句,即默认发送国家“印度”。 - Bhagvat Lande
好的,我明白了。请检查我的编辑和新的 Plunker。 - Antikhippe
显示剩余5条评论

5
您可以使用ngModel来设置PrimeNG Dropdown的默认值,如下所示:
<p-dropdown [options]="cities" name="selectedCity" [(ngModel)]="selectedCity"></p-dropdown>

selectedCity: string = 1; //Id value of the City to be selected

this.cities.value = this.selectedCity;  

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>

只需指定名称选项标签和选项值。

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

因此,标签键的值将用于显示,而值键的值将在ngModel中使用。


3

替代方案,尝试使用:

[placeholder]="yourSelectedObject.Field"

2
我也遇到了这个问题,经过几分钟的调试,我发现造成这个问题的常见原因可能是: 1) 类型不匹配 - 下拉框可以绑定到整数,而[(ngModel)]属性可以是字符串。
例如:
<p-dropdown [options]="countries" [(ngModel)]="selectedCountry"></p-dropdown>

Where

countries = [1,2,3]

并且

selectedCountry = '1'
2) 大小写转换 - 下拉框可以绑定到一个小写字符串上,[(ngModel)] 属性可以是大写,小写或两者的组合。

例如:

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

并且

selectedCountry = 'united states'

为了达到预期的效果,必须完全匹配,本例中为'美国'


那个提示帮助我理解了问题(尤其是#1)。谢谢!通常我使用SelectItem来映射所选内容,但在我的情况下,当下拉值为数字(并且onmodelchange事件返回数字)时,使用SelectItem是无意义的。我将selectedItem切换为“any”,并使用value / id更改选择。 - Robert Ostrowicki

1

如果您不添加 'optionValue',primeng下拉框不知道要设置什么值。 要设置默认值,我们必须在p-dropdown中添加optionValue="value",就像这样:

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

在 .ts 文件中:

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

希望这能帮助到某个人。


1

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上。下拉菜单似乎不会响应代码端的值变化,因此这将强制它在您选择当前值之前不显示下拉菜单。

1

我的解决方案是在设置表单字段(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具有相同的数字类型。

0

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接