在Angular 2中,p下拉列表映射到通过web API调用填充的对象。在API调用之后,ngModel被设置为下拉列表中的某个值。但是,仍然没有值显示为默认值,它仍然显示占位符值。
HTML
<div *ngIf="dropdownDataLoaded" style="display: inline-block">
<span class="dropdown" style="margin-left: 126px;">
<p-dropdown [options]="countryOptions" placeholder="Select" [(ngModel)]="selectedCountryValue" inputStyleClass="dropdown" optionLabel="name" (onChange)="onCountryChange($event)"></p-dropdown>
</span>
</div>
组件:
this.dropdownDataLoaded=false;
setTimeout(() => {
this.databaseService.getCountryList().subscribe((countryList: IDropdownElement[]) => {
this.countryOptions = countryList;
this.dropdownDataLoaded = true;
this.selectedCountryValue = {
"name": "USA"
};
}
IDropdownElement模型:
export interface IDropdownElement {
name: string;
id: string;
type: string;
code: string;
}
此外,参考以下链接,但没有运气。
如何设置PrimeNG p下拉的默认值
ngModel
通过引用而非值绑定。
所以你需要让它指向你列表中的同一个对象。
更改此项:
this.selectedCountryValue = {
"name": "USA"
};
对此:
this.selectedCountryValue = this.countryOptions.find(country => country.name === 'USA');
或者使用compareWith
指令,请在此处阅读更多信息:https://angular.io/api/forms/SelectControlValueAccessor