首页 > 解决方案 > Angular mat-autocomplete - 在不改变输入值的情况下动态地将数据推送到 observable

问题描述

我在 Angular 7 中使用了 mat-autocomplete。

<mat-form-field floatLabel="never">
  <input matInput aria-label="salesRepresentative" type="text" [placeholder]="translationObj.startTypingPlaceholder" autocomplete="off"
    [formControl]="autoCompleteControl" [matAutocomplete]="auto">
  <mat-icon matSuffix class="cursor-pointer">search</mat-icon>
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="createSalesRepString">
    <mat-option *ngFor="let item of salesPickerAutoComplete$ | async;" [value]="item">
      {{item.FirstName}} {{item.LastName}} - (Username: {{item.Username}})
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

下面是我的组件代码。

this.salesPickerAutoComplete$ = this.autoCompleteControl.valueChanges.pipe(
  startWith(''),
  debounceTime(400),
  distinctUntilChanged(),
  switchMap(value => {
    if (value && value.length > 2) {
      return this.getSalesReps(value);
    } else {
      return of(null);
    }
  })
);

getSalesReps(value: string): Observable<any[]> {
  const params = new QueryDto;
  params.$filter = `substringof('${value}',FirstName) or substringof('${value}',LastName)`;
  params.$select = "UserId,FirstName,LastName,Username";
  return from(this.salesRepresentativesService.GetSalesRepresentatives(params))
    .pipe(
      map(response => response.Data),
      catchError(() => { return of(null) })
    );
}

现在,通过输入输入,这与搜索完美结合。

我的问题是我希望列表在加载时自动填充一些项目。

我不确定如何使用这种结构来做到这一点。

谁能告诉我我该怎么做?如何动态推送/更改 mat-autocomplete 中的某些项目?

标签: angularobservableangular-material2angular-material-7mat-autocomplete

解决方案


推荐阅读