Angular中的下拉菜单默认选择

时间:2019-03-11 19:32:34

标签: html angular primeng

我在Angular中有以下下拉列表实现。但是我想将Paris显示为默认值,但是即使我按如下所示将值分配为None,它也会显示1

.html

<p-dropdown [options]="labels" [(ngModel)]="selectedCity" optionLabel="name" (onChange)="cityChanged($event.value)"></p-dropdown>

.ts

interface City{
    name: string;
    value: number;
}
export class CityComponent {

 selectedCity: number = 1;

  constructor() {
    this.labels = [
        {name: 'None', value: 0},
        {name: 'Paris', value: 1},
        {name: 'Rome', value: 2},
        {name: 'London', value: 3},
        {name: 'Istanbul', value: 4},
        {name: 'Amsterdam', value: 5},
        {name: 'Moscow', value: 6},
        {name: 'Zurich', value: 7}
     ];
  }

  cityChanged(city : City)
  {
      this.selectedCity = city.value
  }
}

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为下拉列表期望所选的值与您的选项之一匹配。由于您将选项存储为对象,但将值存储为数字,因此无法找到匹配项。解决此问题的最简单方法是将整个对象存储为selectedCity,并在需要时仅获取值:

export class CityComponent {

 selectedCity = {name: 'Paris', value: 1};

  constructor() {
    this.labels = [
        {name: 'None', value: 0},
        {name: 'Paris', value: 1},
        {name: 'Rome', value: 2},
        {name: 'London', value: 3},
        {name: 'Istanbul', value: 4},
        {name: 'Amsterdam', value: 5},
        {name: 'Moscow', value: 6},
        {name: 'Zurich', value: 7}
     ];
  }

  getSelectedValue(): number {
      return this.selectedCity.value;
  }

  cityChanged(city : City) {
      this.selectedCity = city;
  }
}