中获取选定的项目值

中获取选定的项目值

本文介绍了如何在 Angular 2 Material Autocomplete 中获取选定的项目值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created an autocomplete field with Angular Material and getting country list from web api succesfully.

CountryID -> 项目值(或索引)

CountryID -> item value(or index)

国家 -> 项目文本

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

When I try to get selected item's value (not text) it return the text as expected. But I need to get selected item's value.

这是我的代码:

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; 返回了 CountryID.

it worked fine, this.WeatherSearchForm.get('country').value; returned the CountryID.

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

But in UI side after selecting a country in the autocomplete field now I see the CountryID not Country.

推荐答案

你需要在 标签内使用 [displayWith]="displayFn".此外,您可以将整个对象作为 value 传递.

You need to use [displayWith]="displayFn" inside <md-autocomplete> tag. Also, you have a pass the whole object as 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;
}

您可以从 文档

演示

这篇关于如何在 Angular 2 Material Autocomplete 中获取选定的项目值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:18