I am trying to implement md-autocomplete
of material-2
in angular
. The way its suppose to work is when the user starts typing it would make an http
call to get the data and will display in options. I am able to make the http calls but for some reason it wont show it in options
.
Html :
<md-input-container>
<input mdInput placeholder="Search drug" [mdAutocomplete]="auto" [formControl]="drug" showPanel="false">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let drug of filteredDrugs | async" [value]="drug.drugname">
{{ drug.drugname}}
</md-option>
</md-autocomplete>
TS :
export class DialogAutoComplete {
drug: FormControl;
drugList = [];
filteredDrugs: any;
constructor(public dialogRef: MdDialogRef<DialogAutoComplete>, private getData: GetData) {
this.drug = new FormControl();
//this.filteredDrugs =
this.filteredDrugs = this.drug.valueChanges.startWith(null)
.map(drugname => {
return Array.of(this.getDrugs(drugname)) || [{}];
});
}
getDrugs(val: string) {
console.log("filterdrugs is called ", val);
return val ?
// this.drugList.filter(option => option)
this.getData.getDataForAutoComplete(val).subscribe(
(response: Response) => { console.log(response); return response || []; },
(err) => console.log(err)
)
: [{ drugname: "No Such drug found" }];
}
displayFn(drug) {
console.log("displayfn => ", drug);
return drug == null ? drug : drug.drugname;
}
}
Below is the response of the http
call.
Demo plunker with a different api call but similar response and setup. plunker
Appreciate the help.
Make the filteredDrugs
an observable which gets its data from any service (HttpService) in the format you want .
https://blog.bouzekri.net/2016-05-15-angular2-rxjs-simple-paginated-list-with-search-field
Async as defined by you *ngFor="let drug of filteredDrugs | async"
helps to take the value of filterDrugs
during runtime and hence filteredDrugs
needs to be an Observable.
Helpful link : AutoComplete tutorial
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.