如何在 Angular 2 Material 自动完成中获取选定的项目值

How can I get selected item value in Angular 2 Material Autocomplete

我已经使用 Angular Material 创建了一个自动完成字段并成功地从 Web api 获取了国家/地区列表。

CountryID -> 项目值(或索引)

国家 -> 项目文本

当我尝试获取所选项目的值(不是文本)时,它 return 文本如预期的那样。但我需要获取所选项目的价值。

这是我的代码:

this.WeatherSearchForm.get('country').value; // this returns the selected country name, ex: France

<md-input-container>
  <input mdInput placeholder="Select Country..." [mdAutocomplete]="auto" class="form-control validate filter-input" formControlName="country">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" md-input-name="autocompleteField" required md-input-minlength="2" md-input-maxlength="18"
  md-select-on-match required md-input-minlength="2">
  <md-option *ngFor="let country of countries | async" [value]="country.Country">
    {{ country.Country }}
  </md-option>
</md-autocomplete>

编辑: 在我更改此行后

<md-option *ngFor="let country of countries | async" [value]="country.Country">

对此,

<md-option *ngFor="let country of countries | async" [value]="country.CountryID">

它工作正常,this.WeatherSearchForm.get('country').value; return编辑了 CountryID。

但是在 UI 这边,在自动完成字段中选择一个国家后,现在我看到的是 CountryID 而不是国家。

您需要在 <md-autocomplete> 标签内使用 [displayWith]="displayFn"。此外,您将整个对象传递为 value.

<md-autocomplete #auto="mdAutocomplete" md-input-name="autocompleteField" required md-input-minlength="2" md-input-maxlength="18"
  md-select-on-match required md-input-minlength="2" [displayWith]="displayFn">
  <md-option *ngFor="let country of countries | async" [value]="country">
    {{ country.Country }}
  </md-option>
</md-autocomplete>

在您的组件中,添加:

displayFn(country): string {
      return country ? country.Country : country;
}

您可以从 docs

中的 设置单独的控制和显示值 部分阅读更多相关信息

demo

这是最终的工作版本,希望对其他人有所帮助:

<md-autocomplete #auto="mdAutocomplete" md-input-name="autocompleteField" required md-input-minlength="2" md-input-maxlength="18"
  md-select-on-match required md-input-minlength="2" [displayWith]="displayFn">
  <md-option *ngFor="let country of countries | async" [value]="country">
    {{ country.Country }}
  </md-option>
</md-autocomplete>

selectedCountry:Countries;
displayFn(country: Countries): string {
  this.selectedCountry = country;
  console.log(this.selectedCountry);
  return country ? country.Country : country.CountryID;
}

this.SavetoDB(this.WeatherSearchForm.get('country').value);

SavetoDB(country:Countries)
{
   countryID = parseInt(country.CountryID);
...