0

我正在将应用程序从 AngularJS 升级到 Angular 5。我想通了大部分事情,但仍处于学习过程中,我无法找出将自动完成列表连接到后端的最佳方法。Material Design 网站也没有提到这一点。

这是代码现在的样子:

  <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>

我已经删除了 mat-chip-list 并且只包含了相关代码。

所以我的问题是......现在我从 field.options 获取选项——而不是这个,一旦我开始输入,如何从 http 后端动态加载它们?

谢谢你的帮助!:)

4

1 回答 1

5

您可以使用反应形式来实现这一点。这里的文档: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>

可能需要一些其他功能,例如在此流中过滤以在字符数太少时不触发自动完成等,但这只是您可能遵循的基本示例。

于 2017-11-11T18:40:01.643 回答