您可以使用反應形式來實現這一點。這裏的文檔: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