您可以使用反应形式来实现这一点。这里的文档:https ://angular.io/guide/reactive-forms 。
表单的值变化可以是一个流。您可以根据输入值查询后端。
即(在组件ts文件中):
// define appropriate type for your options, string[] just as an example,
// I don't know what you'll receive from the back-end and use as the option:
public autocompleteOptions$: Observable<string[]>;
constructor(private http: HttpClient) { }
ngOnInit() {
// If you don't know how to have reactive form and subscribe to value changes,
// please consult: https://angular.io/guide/reactive-forms#observe-control-changes
this.autocompleteOptions$ = this.inputFormControl.valueChanges
// this inputFormControl stands for the autocomplete trigger input
.debounceTime(150)
// well, you probably want some debounce
.switchMap((searchPhrase: string) => {
// "replace" input stream into http stream (switchMap) that you'll subscribe in the template with "async" pipe,
// it will run http request on input value changes
return this.http.get('/api/yourAutocompleteEndpoint', { search: {
value: searchPhrase }}
});
}
}
然后,在组件的模板中:
<mat-option [value]="opt.id" *ngFor="let opt of autocompleteOptions$ | async">
{{ opt.name }}
</mat-option>
可能需要一些其他功能,例如在此流中过滤以在字符数太少时不触发自动完成等,但这只是您可能遵循的基本示例。