How to get the selected value of an element in Angular 2 Autocomplete stuff
I have created an autocomplete box with Angular Material and am getting the list of countries from the web api successfully.
CountryID -> item value (or index)
Country -> element text
When I try to get the selected value of an element (not text), it returns text as expected. But I need to get the selected item value.
This is my code:
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>
Edit: After I changed this line
<md-option *ngFor="let country of countries | async" [value]="country.Country">
<md-option *ngFor="let country of countries | async" [value]="country.CountryID">
it worked fine, this.WeatherSearchForm.get('country').value;
returned CountryID.
But in the UI, after selecting a country in the autocomplete box, now I can see that CountryID is not a country.
source to share
You need to use [displayWith]="displayFn"
inside a tag <md-autocomplete>
. Also, you have a pass for the entire 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>
In your compoent add:
displayFn(country): string {
return country ? country.Country : country;
}
You can read more about this in the Customizing individual controls and displays section in the docs
source to share
Here is the final working version, hope it helps someone else:
<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);
...
source to share