如何预先 select Primeng Dropdown 值?

How to pre select Primeng Dropdown values?

我的 angular 应用程序中有包含一组值的 primeng 下拉菜单。

在视图 Screen 中,下拉菜单不显示所选值(保存在 db 中的值)而是显示 'Select'。

HTML :

<p-dropdown    [options]="reasons" [(ngModel)]="selectedReason"   (onChange)="getCompleteReason($event)" styleClass="ui-column-filter" filter="true"> </p-dropdown>

Component.ts

this.reasons = [];
    this.reasons.push({label: 'Select', value: null});
    this.reasons.push({label: 'Reason 1', value: 'Reason 1'});
    this.reasons.push({label: 'Reason 2', value: 'Reason 2'});
    this.reasons.push({label: 'Reason 3', value: 'Reason 3'});
    this.reasons.push({label: 'Other', value: 'Other'});


this.selectedReason = 'Reason 2' (eg value stored in the db)

在我将名称属性添加到下拉列表后它起作用了

<p-dropdown   [options]="reasons" [(ngModel)]="selectedReason"  name="selectedReason"   (onChange)="getCompleteReason($event)" styleClass="ui-column-filter" filter="true">

要预 select 您的 primeng 下拉值,您可以像这样使用 patchValue() 更新您的 formGroup 值:

public parentForm: FormGroup
this.parentForm = this.formBuilder.group({
      group: [null, [Validators.required]],
      id_module:  [null]
    })

const newObj = {group: 'Test', id_module: 32}
this.parentForm.patchValue(newObj )

你也可以试试这个。比方说,您的下拉菜单如下所示:

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