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

Viewed 10984

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

CountryID -> item value(or index)

Country -> item text

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 is my code:

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

and

<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>

Edit: After I changed this line

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

to this,

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

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

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

enter image description here enter image description here

2 Answers
Related