Created
October 5, 2017 22:00
-
-
Save danizen/3d956396e09aa7d521ddf9be08a05d03 to your computer and use it in GitHub Desktop.
Angular 4 server-side autocomplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
} | |
} |
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
Maybe use the answers at https://stackoverflow.com/questions/43575515/md-autocomplete-angular2-getting-data-from-server-with-a-service