如何在Angular 2 Material Autocomplete中获取所选项目值

时间:2017-07-10 16:12:49

标签: angular autocomplete angular-material2

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

CountryID - >商品价值(或指数)

国家/地区 - >项目文本

当我尝试获取所选项目的值(而不是文本)时,它会按预期返回文本。但我需要获得所选项目的价值。

这是我的代码:

locationURI: popup:com.example.navigator.menu

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"> 返回了CountryID。

但是在自动填充字段中选择国家/地区后,在UI端,我看到CountryID不是国家/地区。

enter image description here enter image description here

2 个答案:

答案 0 :(得分:5)

您需要在[displayWith]="displayFn"标记内使用<md-autocomplete>。此外,您将整个对象传递为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

答案 1 :(得分:1)

这是最终的工作版本,希望它可以帮助其他人:

<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);
...