Angular p-dropdown 从一个选项数组动态创建选项

问题描述

我正在尝试在 Angular 中创建多个下拉菜单,并且需要每个下拉菜单显示一个选项。我已经走了这么远,但现在我的下拉菜单总是用一个值初始化。 我有多个下拉列表并尝试使用一个选项数组并根据这些选项生成我的数据。我也不知道我需要多少下拉菜单。 问题是我还需要一个空值,用户有时不想选择值。

https://stackblitz.com/edit/primeng-dropdown-demo-4tffmy?devtoolsheight=33&file=src/app/app.component.ts

最好的问候

解决方法

我不完全确定您要做什么,但这对您要实现的目标有帮助吗?

getOptions(country: Country) {
  let index = this.cities.findIndex(c => c.country === country);
  return this.cities.slice(0,this.cities.length - index);
}

constructor() {
  this.countries = [
    { name: 'USA' },{ name: 'Italy' },{ name: 'UK' },{ name: 'Turkey' },{ name: 'France' }
  ];

  this.cities = [   
    { name: 'New York',code: 'NY',country: this.countries[0] },{ name: 'Rome',code: 'RM',country: this.countries[1] },{ name: 'London',code: 'LDN',country: this.countries[2] },{ name: 'Istanbul',code: 'IST',country: this.countries[3] },{ name: 'Paris',code: 'PRS',country: this.countries[4] }
  ];
}
<p-dropdown [options]="getOptions(country)" [ngModel]="dataBind.get(country)" optionLabel="name"
        (onFocus)="createCityOptions()" editable="true" optionLabel="name"></p-dropdown>

如果没有,并且您可以进一步描述您的意图,我很乐意更新答案。

您可能还想查看此 StackBlitz