Skip to content

Instantly share code, notes, and snippets.

@danizen
Created October 5, 2017 22:00
Show Gist options
  • Save danizen/3d956396e09aa7d521ddf9be08a05d03 to your computer and use it in GitHub Desktop.
Save danizen/3d956396e09aa7d521ddf9be08a05d03 to your computer and use it in GitHub Desktop.
Angular 4 server-side autocomplete
<div class="container">
<div class="row">
<form class="example-form">
<md-form-field class="example-full-width">
<input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto" placeholder="Health Topic Name">
<md-autocomplete #auto="mdAutocomplete">
<md-option *ngFor="let option of serverOptions | async" [value]="option">
{{ option }}
</md-option>
</md-autocomplete>
</md-form-field>
</form>
</div>
</div>
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounce';
import 'rxjs/add/operator/delay';
import { SearchService } from './search.service';
@Component({
selector: 'app-test-material',
templateUrl: './test-material.component.html',
styleUrls: ['./test-material.component.scss'],
providers: [ SearchService ]
})
export class TestMaterialComponent implements OnInit {
myControl: FormControl = new FormControl();
options = [];
serverOptions: Observable<string[]>;
constructor(private searchService: SearchService) { }
ngOnInit() {
this.serverOptions = this.myControl.valueChanges
.delay(new Date(Date.now() + 1000))
.startWith(null)
.map(val => val ? this.findTopics(val) : []);
}
findTopics(val) {
this.searchService.autocomplete(val).then( results => {
console.log(results);
this.options = results;
return results;
});
}
}
@danizen
Copy link
Author

danizen commented Oct 5, 2017

@hizmarck
Copy link

This doesn't work for me, I think that findTopics doesn't return any value, right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment