0

我正在將應用程序從AngularJS升級到Angular 5.我想出了大部分內容,但仍處於學習過程中,並且我無法弄清楚將自動完成列表連接到後端的最佳方式。材料設計網站也沒有提到這一點。角度5材料,從後端服務器獲取mat-options(在自動完成/選擇列表中)

下面的代碼看起來像現在:

<mat-form-field> 

    // chips are up here 

    <mat-autocomplete (optionSelected)="chipAdd($event,field)" #auto="matAutocomplete"> 
     <mat-option [value]="opt.id" *ngFor="let opt of field.options"> 
     {{ opt.name }} 
     </mat-option> 
    </mat-autocomplete> 

    </mat-form-field> 

我已經刪除了墊片列表,只包括相關的代碼。

所以我的問題是......現在我從field.options獲取選項 - 而不是這個,我怎麼能從http後端動態地加載它們,一旦我開始輸入?

感謝您的幫助! :)

回答

1

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

有可能是必需的,就像在此流中過濾不觸發自動完成一些附加功能時字符的數目太低或什麼的,但這只是你可能遵循的基本例子。

+0

絕對完美答案!!!完美的作品。非常感謝Radoslaw :) – Matt