Angular 5材质,从后端服务器获取mat-options(在自动完成/选择列表中)

时间:2017-11-11 17:41:33

标签: angular angular2-forms angular-material2 angular4-httpclient

我将应用程序从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后端动态加载它们?

感谢您的帮助! :)

1 个答案:

答案 0 :(得分:3)

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

可能还需要一些额外的功能,比如在此流中过滤不会在字符数过低或触摸时触发自动完成,但这只是您可能遵循的基本示例。