Angular 使用 Observable 自动完成

Angular autocomplete with Observable

我遇到了 Angular 的自动完成问题,我无法显示名称而不是 ID,正如您在此处看到的那样:

我的数据是可观察的,如下所示:

autocomplete.component.ts:

driverListItem$: Observable<DriverListItem[]>;
ngOnInit() {
    this.driverListItem$ = this.driverListItemService.getList(+subcontractorId);
}

autocomplete.service.ts:

getList(subcontractorId?: number): Observable<DriverListItem[]> {
    return this.http.get<DriverListItem[]>(
      this.apiUrl,
      {
        params: new HttpParams().append('subcontractorId', subcontractorId.toString()),
        headers: this.getAuthHeaders(this.authService.token),
      }
    )
    .do(
      value => console.debug('DriverListItemService getList value', value),
      error => {
          console.debug('DriverListItemService getList error', error);
          this.handleError(error);
      },
    );
  }

autocomplete.component.html:

<mat-form-field style="width:100px">
  <input matInput name="assignedOperator" [(ngModel)]="entity.assignedOperator" [matAutocomplete]="auto" />
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let driver of driverListItem$ | async" [value]="driver.id">{{ driver.firstName + ' ' + driver.lastName }}</mat-option>
  </mat-autocomplete>
</mat-form-field>

查看文档:https://material.angular.io/components/autocomplete/overview#setting-separate-control-and-display-values

If you want the option's control value (what is saved in the form) to be different than the option's display value (what is displayed in the text field), you'll need to set the displayWith property on your autocomplete element. A common use case for this might be if you want to save your data as an object, but display just one of the option's string properties. To make this work, create a function on your component class that maps the control value to the desired display value. Then bind it to the autocomplete's displayWith property.

autocomplete.component.html

<mat-form-field style="width:100px">
    <input matInput name="assignedOperator" 
           [(ngModel)]="entity.assignedOperator" [matAutocomplete]="auto" />
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let driver of driverListItem$ | async" 
                    [value]="driver">{{ driver.firstName + ' ' + 
                   driver.lastName }}</mat-option>
    </mat-autocomplete>
</mat-form-field>

autocomplete.component.ts

displayFn(driver?: DriverListItem): string | undefined {
  return driver ? `${driver.firstname} ${driver.lastname}` : undefined;
}

2018 年 2 月 16 日更新 7:56

使用这种方法,您必须将 mat-option 概率 [value] 设置为 driver。这意味着您的 [(ngModel)]="entity.assignedOperator" 持有您的驱动程序对象。