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