您可以使用反应形式来实现这一点。这里的文档:https://angular.io/guide/reactive-forms。
表单的值更改可以是流。您可以根据输入值查询后端。
I.e. (在组件TS文件):
// define appriopriate type for your options, string[] just as an example,
// I don't know what you'll receive from the backend 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 }}
});
}
}
然后,在HTML:
<mat-option [value]="opt.id" *ngFor="let opt of autocompleteOptions$ | async">
{{ opt.name }}
</mat-option>
有可能是必需的,就像在此流中过滤不触发自动完成一些附加功能时字符的数目太低或什么的,但这只是你可能遵循的基本例子。
绝对完美答案!!!完美的作品。非常感谢Radoslaw :) – Matt