How can I get selected item value in Angular 2 Material Autocomplete
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>
In your compoent, add:
displayFn(country): string { return country ? country.Country : country;}
You can read more about it from Setting separate control and display values section in docs
Here is the final working version, hope it helps anyone 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);...